tsetsee / php-dto
v3.2.1
2024-03-18 08:38 UTC
Requires
- php: ^8.0
- nesbot/carbon: ^2.62
- symfony/property-access: ^4.0 || ^5.0 || ^6.0
- symfony/serializer: ^4.0 || ^5.0 || ^6.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.11
- pestphp/pest: ^2.33.2
- phpstan/phpstan: ^1.8
README
PHP 数据传输对象库
开始使用
您应该通过 TseDTO
扩展您的类。
安装
$ composer require tsetsee/php-dto
功能
toArray()
方法仅基于初始化的数组数据。
<?php namespace Tsetsee\DTO\Tests\DTO; use Carbon\Carbon; use Carbon\CarbonImmutable; use Spatie\DataTransferObject\Attributes\CastWith; use Spatie\DataTransferObject\Attributes\MapTo; use Tsetsee\DTO\Casters\CarbonCaster; use Tsetsee\DTO\DTO\TseDTO; class TestDTO extends TseDTO { public string $firstName; public string $lastName; public ?string $familyName = null; public ?int age = null; } ... $dto = new TestDTO([ 'firstName' => 'Tsetsentsengel', 'lastName' => 'Munkhbayar', // 'familyName' => 'Galzuud', 'age' => 31, ]); var_dump($dto->toArray()); ... [Output] array() { ["firstName"] => string(14) "Tsetsentsengel" ["lastName"] => string(10) "Munkhbayar" ["age"] => int 31 }
处理 DateTime
-
php-dto
支持 symfony 的DateTimeNormalizer
,该工具处理\DateTimeInterface
、\DateTimeImmutable
、\DateTime
。 @see。默认情况下,它使用 RFC3339 格式。
<?php namespace Tsetsee\DTO\Tests\DTO; use Symfony\Component\Serializer\Annotation\Context; use Tsetsee\DTO\Serializer\Normalizer\CarbonNormalizer; use Tsetsee\DTO\DTO\TseDTO; use Carbon\CarbonImmutable; class TestDTO extends TseDTO { #[Context( normalizationContext: [ CarbonNormalizer::FORMAT_KEY => 'c', ], denormalizationContext: [ CarbonNormalizer::FORMAT_KEY => 'm-d-Y H:i:s', ], )] public ?CarbonImmutable $date = null; }
- 从时间戳转换。
<?php namespace Tsetsee\DTO\Tests\DTO; use Carbon\Carbon; use Tsetsee\DTO\DTO\TseDTO; use Symfony\Component\Serializer\Annotation\Context; use Tsetsee\DTO\Serializer\Normalizer\CarbonNormalizer; class TestDTO extends TseDTO { #[Context( denormalizationContext: [ CarbonNormalizer::FORMAT_KEY => 'X', ], )] public ?Carbon $dateFromTimestamp = null; }
数组转换
如果属性是 DTO 的数组,您应该添加 adder 方法
。
<?php namespace Tsetsee\DTO\Tests\DTO; use Carbon\Carbon; use Tsetsee\DTO\DTO\TseDTO; use Symfony\Component\Serializer\Annotation\Context; use Tsetsee\DTO\Serializer\Normalizer\CarbonNormalizer; class TestDTO extends TseDTO { /** * @var array<ChildDTO> */ public array $children = []; public function addChildren(ChildDTO $children): void { $this->children[] = $children; } }