takemo101 / simple-dto
Simple DTO
v0.2.2
2023-08-01 12:08 UTC
Requires
- php: ^8.1
Requires (Dev)
- php: ^8.1
- phpstan/phpstan: ^1.4
- phpunit/phpunit: ^9.5
README
Simple DTO是一个用于创建简单数据对象的库。
享受吧!
安装
执行以下composer命令。
composer require takemo101/simple-dto
基本用法
请按照以下方式使用
<?php use Takemo101\SimpleDTO\Attributes\Getter; use Takemo101\SimpleDTO\Attributes\Ignore; use Takemo101\SimpleDTO\Attributes\Rename; use Takemo101\SimpleDTO\Traits\HasSimpleDTO; class MyDTO { // Use this trait to support arraying and getter methods use HasSimpleDTO; public function __construct( public string $a, // Rename array keys #[Rename('bb')] public string $b, // ignore converting to array #[Ignore] public string $c, ) { // } // When set to a getter method, it can be referenced as a property #[Getter] public function foo(): string { return 'foo'; } // You can change the name you refer to as a property #[Getter('var')] public function bar() { return 'bar'; } } $dto = new MyDTO('a', 'b', 'c'); echo $dto->foo; // foo echo $dto->var; // bar // Convert to array var_dump($dto->toArray()); // ['a' => 'a', 'bb' => 'b', 'foo' => 'foo', 'var' => 'bar']
如何添加将DTO转换为数组的功能
use Takemo101\SimpleDTO\SimpleDTOFacade; // A class that implements the DTOTransformer interface can be given as an argument. // If no arguments are given, the default implementation will be set. SimpleDTOFacade::setup(); class FirstDTO { use HasSimpleDTO; public function __construct( public SecondDTO $second, ) { // } } class SecondDTO { use HasSimpleDTO; public function __construct( public string $text, ) { // } } $dto = new FirstDTO(new SecondDTO('text')); // DTO is arrayed by default DTOTransformer. var_dump($dto->toArray()); // ['second' => ['text' => 'text']]
如何从数组重新构建DTO
use Takemo101\SimpleDTO\SimpleDTOFacade; // omit... // Reconstructs the DTO from the array, so it can be both arrayed and objectified $dto = FirstDTO::fromArray(['second' => ['text' => 'text']]);