Data Transfer Objects
You may wish to cast the data you receive in an API response to a data transfer object (DTO). Saloon has a built-in plugin that makes this easy. With this plugin, you can specify the DTO on a per-request basis.
Configuring
Firstly, add the CastsToDto trait to your request.
After that, add the castToDto
method to your request. It has one argument which is an instance of SaloonResponse. This method is only run after a successful response has been received from the API. This method should return your data transfer object fully constructed from the response data you received.
This is how my data transfer object looks internally. I have created a fromSaloon
method however you can use any method of populating your DTO.
Retrieving your DTO
Finally, when you retrieve a successful response from the API, you can use the dto()
method on the response to get the fully constructed DTO.
Saloon will only cast the response to your DTO if the response was successful.
Last updated