Package
laravel-data-object-tools
A set of tools to make working with Data Transfer Objects easier in Laravel
dev-main14,614 downloads67 stars
This package is aimed to be a suite of tools to help working with DTOs even easier. It includes an artisan command to generate DTOs as well as a facade to help you hydrate them.
Installation
composer require juststeveking/laravel-data-object-toolsUsage
To generate a new DTO all you need to do is run the following artisan command:
php artisan make:dto MyDtoThis will generate the following class: app/DataObjects/MyDto.php. By default this class
will be a final class that implements a DataObjectContract which enforces a method toArray so that you can
easily cast your DTOs to arrays.
If you are using PHP 8.2 however, you will by default get a readonly class generated, so that you do not have
to declare each property as readonly.
To work with the hydration functionality you can either use Laravels DI container, or the ready made facade.
Using the container:
class StoreController{ public function __construct( private readonly HydratorContract $hydrator, ) {}
public function __invoke(StoreRequest $request) { $model = Model::query()->create( attributes: $this->hydrator->fill( class: ModelObject::class, parameters: $request->validated(), )->toArray(), ); }}To work with the facade, you can do something very similar:
class StoreController{ public function __invoke(StoreRequest $request) { $model = Model::query()->create( attributes: Hydrator::fill( class: ModelObject::class, parameters: $request->validated(), )->toArray(), ); }}Object Hydration
Under the hood this package uses an EventSauce package, created by Frank de Jonge. It is possibly the best package I have found to hydrate objects nicely in PHP. You can find the documentation here if you would like to see what else you are able to do with the package to suit your needs.
Testing
To run the test suite:
composer run testCredits
LICENSE
The MIT License (MIT). Please see License File for more information.
Related
More Packages
mavis
Run a freelance business from plain files: clients, calls and follow-ups, time, quotes and invoices as Markdown, from one Go binary, with an MCP server for agents.
v0.1.3
PHPcloudevents
Cloud Events in PHP.
dev-main
PHPcompanies-house-laravel
A Laravel wrapper to get companies house information and validate company numbers
v1.2.0
Same subject
In other formats
The Job And The Controller Disagree
The same operation runs from two entry points and they have quietly drifted. In Laravel that drift has a predictable shape, because validation lives at the edge and only one edge has it.
Architecture
VideoData Modeling with Jim Seconde
Join me and Jim Seconde as we go through a data modelling exercise for a Laravel application. We have recently taken on a rescue project to help a company out, our first step is modeling the data so w
Architecture