承接 php-collective/laravel-dto 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

php-collective/laravel-dto

Composer 安装命令:

composer require php-collective/laravel-dto

包简介

Laravel integration for php-collective/dto

README 文档

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
    'typescript_output_path' => resource_path('js/types'), // TypeScript output
    'jsonschema_output_path' => resource_path('schemas'),  // JSON Schema output
];

Usage

1. Initialize DTO configuration

php artisan dto:init

This creates a config/dto.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. Generate TypeScript interfaces

php artisan dto:typescript
php artisan dto:typescript --multiple-files --readonly

4. Generate JSON Schema

php artisan dto:jsonschema
php artisan dto:jsonschema --multiple-files

5. Use your DTOs

use App\Dto\UserDto;

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

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

Eloquent Integration

Attribute Casting

use App\Dto\ProfileDto;
use App\Dto\TagDto;
use PhpCollective\LaravelDto\Eloquent\DtoCast;
use PhpCollective\LaravelDto\Eloquent\DtoCollectionCast;
use PhpCollective\LaravelDto\Eloquent\HasDtoCasts;

class User extends Model
{
    protected $casts = [
        'profile' => DtoCast::class . ':' . ProfileDto::class,
        'tags' => DtoCollectionCast::class . ':' . TagDto::class,
    ];
}

$user = User::firstOrFail();
$profile = $user->profile;       // ProfileDto instance
$tags = $user->tags;             // Collection<TagDto>|null

Or opt into automatic casts:

class User extends Model
{
    use HasDtoCasts;

    protected array $dtoCasts = [
        'profile' => ProfileDto::class,
        'tags' => [
            'class' => TagDto::class,
            'collection' => true,
        ],
    ];
}

Model to DTO

use App\Dto\UserDto;
use PhpCollective\LaravelDto\Eloquent\CreatesDtoFromModel;

class User extends Model
{
    use CreatesDtoFromModel;

    protected function getDtoClass(): ?string
    {
        return UserDto::class;
    }
}

$dto = $user->toDto();

You can also extend the base model:

use PhpCollective\LaravelDto\Eloquent\DtoModel;

class User extends DtoModel
{
    protected function getDtoClass(): ?string
    {
        return UserDto::class;
    }
}

Mapping Helpers

use App\Dto\UserDto;
use PhpCollective\LaravelDto\Eloquent\DtoMapper;

$user = User::with('posts')->firstOrFail();
$dto = DtoMapper::fromModel($user, UserDto::class, relations: ['posts']);

$dtos = DtoMapper::fromCollection(User::query()->get(), UserDto::class);
$paginator = DtoMapper::fromPaginator(User::query()->paginate(), UserDto::class);

API Resources

use PhpCollective\LaravelDto\Http\DtoResource;

return new DtoResource($dto);
// or
return DtoResource::collection($dtos);

Request Integration

DtoFormRequest

use PhpCollective\LaravelDto\Http\DtoFormRequest;

class StoreUserRequest extends DtoFormRequest
{
    protected string $dtoClass = UserDto::class;

    public function rules(): array
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
        ];
    }
}

// In controller:
public function store(StoreUserRequest $request): JsonResponse
{
    $dto = $request->toDto();
    // ...
}

DtoResolver

Register once (e.g. in AppServiceProvider::boot()):

use PhpCollective\LaravelDto\Http\DtoResolver;

DtoResolver::register();

Then inject DTOs directly:

public function store(UserDto $dto): JsonResponse
{
    // $dto is built from request data
}

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.).

Validation Bridge

Convert DTO validation rules to Laravel validation arrays with DtoValidationRules::fromDto(). Integrates directly with Form Requests. See Usage Guide for details.

Supported Config Formats

The package supports multiple config file formats:

  • dto.php - PHP format (default)
  • dto.xml - XML format
  • dto.yml / dto.yaml - YAML format
  • dto/ subdirectory with multiple files

License

MIT

php-collective/laravel-dto 适用场景与选型建议

php-collective/laravel-dto 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 12 月 16 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「dto」 「data-transfer-object」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 php-collective/laravel-dto 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 php-collective/laravel-dto 我们能提供哪些服务?
定制开发 / 二次开发

基于 php-collective/laravel-dto 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 16
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-16