antwerpes/data-transfer-object
最新稳定版本:1.0.5
Composer 安装命令:
composer require antwerpes/data-transfer-object
包简介
Simple json encoding and decoding for PHP data objects
关键字:
README 文档
README
Simple library for encoding and decoding JSON structures into PHP objects, e.g. to work with API responses in a strongly typed way.
Installation
You can install the package via composer:
composer require antwerpes/data-transfer-object
Usage
Define a class that extends Antwerpes\DataTransferObject\DataTransferObject and define the structure of the object:
use Antwerpes\DataTransferObject\Attributes\Cast; use Antwerpes\DataTransferObject\Attributes\Map; use Antwerpes\DataTransferObject\Casts\ArrayCaster; use Antwerpes\DataTransferObject\DataTransferObject; class User extends DataTransferObject { public function __construct( public string $name, #[Cast(CustomDateCaster::class)] public DateTimeInterface $birthday, #[Map(from: 'address.city')] public string $city, #[Cast(ArrayCaster::class, itemType: Interest:class)] public array $interests, ) {} }
Then you can use the class to decode JSON strings into PHP objects:
$json = '{ "name": "John Doe", "birthday": "1990-01-01", "address": { "city": "New York" }, "interests": [ { "name": "Music" }, { "name": "Programming" } ] }'; $user = User::decode(json_decode($json, true)); $encoded = $user->encode();
Custom Casters
You can define custom casters by implementing the Antwerpes\DataTransferObject\CastsProperty interface:
use Antwerpes\DataTransferObject\CastsProperty; class CustomDateCaster implements CastsProperty { public function unserialize(mixed $value): DateTimeInterface { return new DateTime($value); } public function serialize(mixed $value): string { return $value->format('Y-m-d'); } }
Mapping
You can map nested properties to a flat structure using the Map attribute:
use Antwerpes\DataTransferObject\Attributes\Map; class User extends DataTransferObject { public function __construct( #[Map(from: 'address.city', to: 'address.city')] public string $city, ) {} }
Validation
Validation is out of scope for this package, use JSON schemas or other libraries like symfony/validator
to validate the object.
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Contributions are welcome! Leave an issue on GitHub, or create a Pull Request.
Credits
License
The MIT License (MIT). Please see License File for more information.
统计信息
- 总下载量: 62.27k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 2
- 依赖项目数: 2
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-09-12