Using DTOs to keep context

DTOs, or Domain Transfer Objects, can be used for so much. Since PHP 8 was released, creating these fantastic classes in your projects has never been easier.

From escaping the basic construct of an Array to adding type safety to what used to be just a plain old array. In pre-PHP 8, things were possible; it took much more boilerplate code and never felt worthwhile.

With PHP 8.2 looming on the horizon, our options are opening up more and more in the PHP ecosystem. A great book to read would be Object Design Style Guide by Matthias Noback, which I recommend all developers should read at least once.

I, however, do not call these DTOs as I don’t just use them within my domain code. Instead, I call these Data Objects, as that is what they are. For the remainder of this tutorial, I will refer to them as Data Objects.

When creating Data Objects, I like to make all of the properties readonly as they should only ever be read, not written – it defeats the point of them. This gives me an immutable structure I can pass through my application to keep context and type safety – which I call a win-win situation.

Let’s look at an example. I will borrow the idea from the Laravel Bootcamp and create Chirps. Our chirp has two things it needs to care about, its’ message and the user who created it. When building applications these days, I either use UUIDs or ULIDs, depending on the application. In this one, I will use ULIDs.

So we want to refactor the Bootcamp code base to make it easier to manage in the long run – web interface, API, CLI, etc. So we look to move from inline logic in our application to shared classes. Let’s see what this looks like.

1$validated = $request->validate([

2 'message' => 'required|string|max:255',





7return redirect(route('chirps.index'));

We can refactor this so that we do our validation in a Form Request and move the creation over to something else.

1public function __invoke(StoreRequest $request): Response


3 return new JsonResponse(

4 data: $this->command->handle(

5 chirp: $request->validated(),

6 ),

7 status: Http::CREATED->value,

8 );


Here we are returning and handling everything in one go – this can make it a little hard to read, so let’s split this out.

1$chirp = $this->command->handle(

2 chirp: $request->validated(),


This is fine, and there is no reason you have to go further than this. However, if you want to do more and start adding context, then you can begin adding Data Objects which are – in my opinion – nice to use.

How should our chirp look? What would be helpful to us? Let’s look at what I used and talk through the decision process.

1final class ChirpObject implements DataObjectContract


3 public function __construct(

4 public readonly string $user,

5 public readonly string $message,

6 ) {}


8 public function toArray(): array

9 {

10 return [

11 'message' => $this->message,

12 'user_id' => $this->user,

13 ];

14 }


So, in typical Steve fashion, this is a final class. It implements an interface called DataObjectContract, which comes from one of the Laravel packages I typically pull into a project. Each property is public and accessible outside the class, but they are also readonly so that my context can’t change as soon as the object has been created. I then have a method called toArray, which is enforced by the interface, and it is a way for me to implement how this object should be sent to Eloquent.

Using this approach allows me to use a contextual object and add extra type safety to the application. This means that I can rest easy when passing data around my application. How does our controller now look?

1public function __invoke(StoreRequest $request): Response


3 return new JsonResponse(

4 data: $this->command->handle(

5 chirp: new ChirpObject(

6 user: strval(auth()->id()),

7 message: strval($request->get('message')),

8 ),

9 ),

10 status: Http::CREATED->value,

11 );


This code, to me, is ideal. We might want to wrap our code in a try-catch block to catch any potential issues, but that isn’t quite the point I am trying to get across right now.

So far, the biggest issue I have found is that creating Data Objects is sometimes a bit of a pain, especially as they get bigger. If I am working in a larger application, where the Data Objects are larger, I will use a slightly different approach. In this example, I wouldn’t use it. However, in the interest of showing you how you can use it – I will show you this now:

1final class StoreController


3 public function __construct(

4 private readonly ChirpFactoryContract $factory,

5 private readonly CreateNewChirpContract $command,

6 ) {}


8 public function __invoke(StoreRequest $request): Response

9 {

10 return new JsonResponse(

11 data: $this->command->handle(

12 chirp: $this->factory(

13 data: [

14 ...$request->validated(),

15 'user' => strval(auth()->id()),

16 ]

17 ),

18 ),

19 status: Http::CREATED->value,

20 );

21 }


Creating a Data Object Factory will allow us to control how the Data Objects are created and allow us to transform the incoming request into something closer to how we want to work in our application. Let’s look at what the Data Object Factory would look like.

1final class ChirpFactory implements ChirpFactoryContract


3 public function make(array $data): DataObjectContract

4 {

5 return new ChirpObject(

6 user: strval(data_get($data, 'user')),

7 message: strval(data_get($data, 'message')),

8 );

9 }


They are only simple classes that take the request array to turn it into an object, but as the request payload gets larger, these help clean up your controller code.

Have you found exciting ways to use Data Objects? How do you handle their creation? I used to add static creation methods to my Data Objects – but it felt like I was mixing the purpose of the Data Object itself. Let us know your thoughts on Twitter!

Source link


Leave a Reply

Your email address will not be published. Required fields are marked *