php-collective/laravel-dto

Laravel integration for php-collective/dto

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/php-collective/laravel-dto

0.1.1 2026-02-01 08:27 UTC

This package is auto-updated.

Last update: 2026-02-01 19:01:06 UTC


README

Laravel integration for php-collective/dto.

Installation

composer require php-collective/laravel-dto

The service provider will be auto-discovered.

Configuration

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
];

Usage

1. Initialize DTO configuration

php artisan dto:init

This creates a config/dtos.php file with a sample DTO definition (PHP format is the default). You can also use --format=xml or --format=yaml.

The generated config looks like:

use PhpCollective\Dto\Builder\Dto;
use PhpCollective\Dto\Builder\Field;
use PhpCollective\Dto\Builder\Schema;

return Schema::create()
    ->dto(Dto::create('User')->fields(
        Field::int('id'),
        Field::string('name'),
        Field::string('email')->nullable(),
    ))
    ->toArray();

2. Generate DTOs

php artisan dto:generate

Options:

  • --dry-run - Preview changes without writing files
  • -v - Verbose output

3. Use your DTOs

use App\Dto\UserDto;

$user = new UserDto([
    'id' => 1,
    'name' => 'John Doe',
    'email' => 'john@example.com',
]);

return response()->json($user->toArray());

Collections

The service provider automatically registers Laravel's Illuminate\Support\Collection for DTO collection fields. Define collection fields with the [] suffix:

Field::array('roles', 'Role'),  // Role[] collection
Field::array('tags', 'string'), // string[] collection

After generating, collection fields use Laravel's Collection class with all its methods (filter, map, pluck, etc.).

Supported Config Formats

The package supports multiple config file formats:

  • dtos.php - PHP format (default, use dtos.php to avoid conflict with config/dto.php)
  • dto.xml or dtos.xml - XML format
  • dto.yml / dto.yaml or dtos.yml / dtos.yaml - YAML format
  • dto/ subdirectory with multiple files

License

MIT