php-collective/dto
Composer 安装命令:
composer require php-collective/dto
包简介
Framework-agnostic Data Transfer Object library with code generation
README 文档
README
Framework-agnostic DTO library with code generation for PHP.
Unlike runtime reflection libraries, this library generates optimized DTO classes at build time, giving you:
- Zero runtime reflection overhead
- Perfect IDE autocomplete with real methods
- Excellent static analysis support (PHPStan/Psalm work out of the box)
- Reviewable generated code in pull requests
- JSON Schema generation for API documentation
- Schema importer to bootstrap DTOs from JSON data or OpenAPI specs
See Motivation for why code generation beats runtime reflection.
Installation
composer require php-collective/dto
Quick Start
Define DTOs in PHP (or XML, YAML, NEON):
// config/dto.php use PhpCollective\Dto\Config\Dto; use PhpCollective\Dto\Config\Field; use PhpCollective\Dto\Config\Schema; return Schema::create() ->dto(Dto::create('Car')->fields( Field::string('color'), Field::dto('owner', 'Owner'), )) ->dto(Dto::create('Owner')->fields( Field::string('name'), )) ->toArray();
Generate and use:
vendor/bin/dto generate
$car = CarDto::createFromArray(['color' => 'red']); $car->setOwner(OwnerDto::create(['name' => 'John'])); $array = $car->toArray();
See the documentation for detailed examples.
Immutable DTOs
A more realistic example using immutable DTOs for a blog system:
// config/dto.php return Schema::create() ->dto(Dto::immutable('Article')->fields( Field::int('id')->required(), Field::string('title')->required(), Field::string('slug')->required(), Field::string('content'), Field::dto('author', 'Author')->required(), Field::collection('tags', 'Tag')->singular('tag'), Field::bool('published')->default(false), Field::string('publishedAt'), )) ->dto(Dto::immutable('Author')->fields( Field::string('name')->required(), Field::string('email'), Field::string('avatarUrl'), )) ->dto(Dto::immutable('Tag')->fields( Field::string('name')->required(), Field::string('slug')->required(), )) ->toArray();
// Creating from API/database response $article = ArticleDto::createFromArray($apiResponse);
Reading in a template (e.g., Twig, Blade, or plain PHP):
<!-- templates/article/view.php -->
<article>
<h1><?= htmlspecialchars($article->getTitle()) ?></h1>
<p class="meta">
By <?= htmlspecialchars($article->getAuthor()->getName()) ?>
<?php if ($article->getPublishedAt()) { ?>
on <?= $article->getPublishedAt() ?>
<?php } ?>
</p>
<div class="tags">
<?php foreach ($article->getTags() as $tag) { ?>
<a href="/tag/<?= $tag->getSlug() ?>"><?= htmlspecialchars($tag->getName()) ?></a>
<?php } ?>
</div>
<div class="content">
<?= $article->getContent() ?>
</div>
</article>
Features
- Types:
int,float,string,bool,array,mixed, DTOs, classes, enums - Union types:
int|string,int|float|string - Collections:
'type' => 'Item[]', 'collection' => truewith add/remove/get/has methods - Associative collections: keyed access with
'associative' => true - Immutable DTOs:
'immutable' => truewithwith*()methods - Readonly properties:
public readonlywith direct property access - Validation rules: built-in
minLength,maxLength,min,max,patternconstraints - Lazy properties: deferred DTO/collection hydration with
asLazy() - Default values:
'defaultValue' => 0 - Required fields:
'required' => true - Deprecations:
'deprecated' => 'Use newField instead' - Inflection: automatic snake_case/camelCase/dash-case conversion
- Deep cloning:
$dto->clone() - Nested reading:
$dto->read(['path', 'to', 'field']) - PHPDoc generics:
@var \ArrayObject<int, ItemDto>for static analysis - TypeScript generation: Generate TypeScript interfaces from your DTO configs
- Schema Importer: Auto-create DTOs from JSON data or JSON Schema
Configuration Formats
- PHP - native arrays or fluent builder
- XML - XSD validation, IDE autocomplete
- YAML - requires
pecl install yaml - NEON - requires
nette/neon
TypeScript Generation
Generate TypeScript interfaces directly from your DTO configuration - keeping frontend and backend types in sync:
# Single file output vendor/bin/dto typescript --config-path=config/ --output=frontend/src/types/ # Multi-file with separate imports vendor/bin/dto typescript --multi-file --file-case=dashed --output=types/
// Generated: types/dto.ts export interface UserDto { id: number; name: string; email: string; address?: AddressDto; roles?: RoleDto[]; }
Options: --readonly, --strict-nulls, --file-case=pascal|dashed|snake
See TypeScript Generation for full documentation.
Schema Importer
Bootstrap DTO configurations from existing JSON data or JSON Schema definitions:
use PhpCollective\Dto\Importer\Importer; $importer = new Importer(); // From API response example $json = '{"name": "John", "age": 30, "email": "john@example.com"}'; $config = $importer->import($json); // From JSON Schema $schema = file_get_contents('openapi-schema.json'); $config = $importer->import($schema, ['format' => 'xml']);
Outputs to PHP, XML, YAML, or NEON format. Perfect for integrating with external APIs.
See Schema Importer for full documentation.
Documentation
Full documentation available at php-collective.github.io/dto
- Getting Started - Quick start guide with examples
- Configuration Builder - Fluent API for defining DTOs
- Runtime API - Core DTO methods and global runtime options
- Examples - Practical usage patterns
- Circular Dependencies - How generation-time cycle detection works
- TypeScript Generation - Generate TypeScript interfaces
- JSON Schema Generation - Generate JSON Schema for DTO definitions
- Schema Importer - Bootstrap DTOs from JSON data/schema
- Performance - Benchmarks and optimization tips
Integrations
This is the standalone core library. For framework-specific integrations:
- CakePHP: dereuromark/cakephp-dto - Bake commands, plugin
- Laravel: php-collective/laravel-dto - Artisan commands, service provider
- Symfony: php-collective/symfony-dto - Console commands, bundle integration
php-collective/dto 适用场景与选型建议
php-collective/dto 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 13.93k 次下载、GitHub Stars 达 28, 最近一次更新时间为 2025 年 12 月 14 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「php」 「dto」 「code-generation」 「data-transfer-object」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 php-collective/dto 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 php-collective/dto 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 php-collective/dto 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
PHP library for the MUMSYS project
A simple library that allows transform any kind of data to native php data or whatever
Data transfer objects
Convert doctrine dbal query result to dto
Git manager and platform provider for Laravel — facades, typed DTOs, test fakes, and scoped repositories.
Flexible Laravel package for managing external database connections with Redis cache and HTTP API fallback. Supports customizable DTOs and multiple connection types for microservices architecture.
统计信息
- 总下载量: 13.93k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 28
- 点击次数: 25
- 依赖项目数: 5
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-12-14