April 25, 2024
Breaking News

Data Transfer Object V3 Modernizes DTOs With PHP 8 Features – Laravel News

Spatie’s Data Transfer Object (DTO) package makes constructing objects from arrays a breeze, giving you confidence in the data contained therein. I’ve been a fan of this package since learning about the initial V1 release, and I hope you’ll consider this package for passing around data in your application.

The DTO package just released V3 with all of the PHP 8 goodies we’ve only dreamed of up to this point. For those just starting to use or consider PHP 8 in your projects, the source code of the V3 DTO package is an excellent resource with real-world examples of helpful PHP 8 features.

I want to congratulate the principal author Brent Roose and Spatie for moving forward with this excellent package with the features in the V3 release.

Here are some of the main features taken from the readme available in V3:

  • Named arguments
  • Value Casts – convert properties typed as a DTO from array data to the DTO instance automatically
  • Custom Casts – you can build your custom caster classes
  • Strict DTOs
  • Helper functions
  • Runtime type checks are gone in favor of PHP 8’s type system

If you want all the details of the above features, check out the project’s readme.

While the DTO package readme delves into the more complex use-cases this package supports, here’s a simple example back from V1 of what you might expect from this package for those not familiar with the DTO package:

1class PostData extends DataTransferObject

2{

3 /** @var string */

4 public $title;

5 

6 /** @var string */

7 public $body;

8 

9 /** @var int */

10 public $author_id;

11}

12 

13$postData = new PostData([

14 'title' => '…',

15 'body' => '…',

16 'author_id' => '…',

17]);

18 

19$postData->title;

20$postData->body;

21$postData->author_id;

As you can see, we can pass array data to the constructor, which (at the time of V1) checks types at runtime and constructs a PostData instance or fails in an exception if the data is not valid.

With the release of typed properties in PHP 7.4 and named arguments and union types in PHP 8, Spatie’s V3 of the DTO package leverages many new language features. Taking the simple example above, here’s what it might look like in a PHP 8 version:

1use SpatieDataTransferObjectDataTransferObject;

2 

3class PostData extends DataTransferObject

4{

5 public string $title;

6 public string $body;

7 public int $author_id;

8}

9 

10// Named arguments FTW

11$post = new PostData(

12 title: 'Hello World',

13 body: 'This is a test post.',

14 author_id: 1

15);

16 

17echo $post->title, "n";

18echo $post->body, "n";

19echo $post->author_id, "n";

The above example is simple but illustrates well how this package’s basics have evolved since V1, which supports PHP ^7.0. Note: given the above example, you might not even need to leverage the DTO package as PHP 8 takes care of the typing concerns and allows named arguments making a plain old PHP object (POPO) just as practical for this simple example.

If you haven’t tried Spatie’s DTO package, I hope even this simple example illustrates how you can know more about the data you transfer between objects. Imagine the above as an array of data:

1$post = [

2 'title' => 'Hello World',

3 'body' => 'This is a test post.',

4 'author_id' => 1,

5];

6 

7$someObject->doStuff($post);

Let’s say that your doStuff implementation looks like the following to keep the example simple:

1function doStuff(array $post)

2{

3 $title = ucwords($post['title']);

4 $author = findAuthorById($post['author_id']);

5 

6 echo $title, "n";

7 echo htmlspecialchars($post['body']);

8 echo $author['name'], "n";

9}

As a consumer of doStuff(), you have no idea the shape of the required data without referencing the implementation of doStuff(). That means when you need to call doStuff(), you have to look at the function to know what array data to pass.

The maintainer of a naive doStuff() implementation assumes that the consumer is sending required data. Sending malformed or missing data results in undefined key errors that might not crop up until after you’ve shipped a feature. Or, if you’re paranoid, you might need to check everything before you use it:

1function doStuff(array $post)

2{

3 if (empty($post['title'])) {

4 throw new Exception('Missing title');

5 }

6 

7 if (empty($post['body'])) {

8 throw new Exception('Missing body');

9 }

10 

11 if (empty($post['author_id'])) {

12 throw new Exception('Missing author_id key');

13 }

14 

15 $title = ucwords($post['title']);

16 $author = findAuthorById($post['author_id']);

17 

18 echo $title, "n";

19 echo htmlspecialchars($post['body']);

20 echo $author['name'], "n";

21}

Instead, you could guarantee the shape of data with a POPO or DTO (back in V1). It’s just that in DTO V2 and V3, some things are now handled natively through PHP 8’s language features instead of runtime checks:

1function doStuff(PostData $post)

2{

3 $author = findAuthorById($post->author_id);

4 

5 echo $post->title, "n";

6 echo htmlspecialchars($post->body);

7 echo $author->name, "n";

8}

IDEs understand PostData, making it easy to both use and construct new instances. In this naive example, we know what data to expect, and the DTO package ensures this data is structured as expected when the object gets constructed.

While structured, typed data might seem like a trivial boilerplate to the veteran Java developer, PHP developers are more prone to seeing associative array data passed back and forth in an application. PHP 8 and this DTO package go a long way in providing more assurances of the data passed around in your PHP applications, which I believe makes you more productive and your code more confident.

Learn More

You can learn more about this package, get full installation instructions, and view the source code on GitHub. Freek Van der Herten and Brent Roose also wrote details of the Data Transfer Object v3 features if you’re looking for a more in-depth explanation and examples of the DTO package.