Usage
Data transfer objects are useful to pass data, they can be used everywhere but has some special uses in multiple places like controllers (including their route bindings) and queued jobs.
Usage as standalone
Remember that using the constructor like new CreatePostData
is also a valid option but it will not map all the data.
You can use DTOs on every place you want as the following:
Usage in controllers
Now at the controller level you may do something like the following:
This can be also be shorter by injecting directly the DTO like the following:
But then you might also think that your data must be validated, then you should read the following section.
Validating request data
To be able to send a FormRequest
that will also run validation inside the DTO you may need to create a ValidatedDataTransferObject
.
The best way to do so is by running the following command:
You can also specify the FormRequest
class path so it will be injected directly:
This way will try reading validation rules array from the FormRequest
then add them as properties to the DTO class with their types and, if nullable, adding default value as null.
This way you will have something like the following:
Now whenever you use this DTO on your controllers sending your FormRequest
instance or injecting it directly in your controller methods will run validation on the data provided.
Usage in queued jobs
The usage on queued jobs is automatically performed by the package itself, it will serialise and deserialise all the data from the DTO when the queued job enters to the queues processor.
Just adding an example to clarify its usage, having the following queued job:
Then sending this job to the queue with the data transfer object already created using fromArray
or fromRequest
methods or via controller binding:
Last updated