Laravel integration for php-collective/dto.
composer require php-collective/laravel-dtoThe service provider will be auto-discovered.
Publish the config file:
php artisan vendor:publish --provider="PhpCollective\LaravelDto\DtoServiceProvider"This creates config/dto.php with the following options:
return [
'config_path' => config_path(), // Where DTO config files are located
'output_path' => app_path('Dto'), // Where to generate DTOs
'namespace' => 'App\\Dto', // Namespace for generated DTOs
];Create config/dto.xml (or config/dtos.xml to avoid conflicts):
<?xml version="1.0" encoding="UTF-8"?>
<dtos xmlns="php-collective-dto">
<dto name="User">
<field name="id" type="int"/>
<field name="name" type="string"/>
<field name="email" type="string"/>
</dto>
</dtos>php artisan dto:generateOptions:
--dry-run- Preview changes without writing files-v- Verbose output
use App\Dto\UserDto;
$user = new UserDto();
$user->setId(1);
$user->setName('John Doe');
$user->setEmail('john@example.com');
return response()->json($user->toArray());Or create from an array:
$user = UserDto::createFromArray([
'id' => 1,
'name' => 'John Doe',
'email' => 'john@example.com',
]);The package supports multiple config file formats:
dto.xmlordtos.xml- XML formatdto.yml/dto.yamlordtos.yml/dtos.yaml- YAML formatdtos.php- PHP format (usedtos.phpto avoid conflict withconfig/dto.php)dto/subdirectory with multiple files
MIT