uvarats / dto
用于创建PHP 8 dto的轻量级库,支持构造函数提升字段
v0.3.0
2023-05-05 16:24 UTC
Requires
- php: >=8.2
Requires (Dev)
- fakerphp/faker: ^1.21
- phpunit/phpunit: ^10.0
- symfony/var-dumper: ^6.2
README
最初这个包是为内部使用开发的,但后来我决定发布。
安装
composer require uvarats/dto
要求:PHP 8.2
支持
- DTO填充
- 枚举属性
- DTO数组
使用方法
只需通过您的DTO扩展Data类。
然后,只需通过YourDto::from($data)创建DTO对象,其中$data是包含数据的数组。此数组必须与类字段具有相同的映射(数组根目录中无'data')。
示例
final class LoginDto extends Data { public function __construct( public readonly ?string $username = null, public readonly ?string $password = null, ) { } }
然后
$data = [ 'username' => 'some_user', 'password' => '123456' ]; $dto = LoginDto::from($data); // Collection $data = [ [ 'username' => 'some_user', 'password' => '123456' ], [ 'username' => 'some_user', 'password' => '123456' ], ]; $dtos = LoginDto::collection($data);
也支持嵌套数据和枚举
enum State: string { case NEW = 'new'; case UNDER_MODERATION = 'under_moderation'; case PUBLISHED = 'published'; } final class AuthorDto extends Data { public function __construct( public readonly string $userId, public readonly string $username, ) { } } final class ExampleDto extends Data { public function __construct( public readonly string $name, public readonly State $state, public readonly AuthorDto $author ) { } }
$data = [ 'name' => 'Some name', 'state' => 'new', 'author' => [ 'userId' => '232', 'username' => 'user', ] ];
如果非空属性没有默认值且未在数组中,将抛出异常。构造函数属性必须是严格类型。联合和交集是禁止的。
final class TestDto extends Data { public function __construct( public $name, // Exception public string|array $id, // Exception public callable&iterable $caliterable // Also exception ) { } }