kirillbdev / php-data-transformer
将数据转换为类型化对象
v1.1.0
2021-10-02 16:08 UTC
Requires (Dev)
- phpunit/phpunit: ^8.5.8
README
此包帮助您将自定义数据转换为类型化对象。
安装
使用 composer
composer require kirillbdev/php-data-transformer ^1.0.0
示例
1. 将数据数组转换为 DTO
首先创建一个简单的 DTO 类。
namespace MyApp\Dto; class UserDto { public $id; public $firstname; }
现在,使用 DataTransformer,将任意数据数组转换为我们自己的 DTO。
namespace MyApp; use kirillbdev\PhpDataTransformer\DataTransformer; use kirillbdev\PhpDataTransformer\DataObject\ArrayDataObject; use MyApp\Dto\UserDto; $dto = DataTransformer::transform(UserDto::class, new ArrayDataObject([ 'id' => 1, 'firstname' => 'Jon' ]));
DtoTransfer 类将绕过我们的 Dto 的所有公共属性,并自动从输入数据对象(在我们的情况下是一个数组)中获取值。如您所见,这很简单。
2. 从 DataObject 接收自定义键
有时输入数据的键与我们的 DTO 的属性名称不同。在这种情况下,我们可以使用 @ReceiveFrom
注解来接收所需属性的数据。
namespace MyApp\Dto; class UserDto { public $id; /** * We need to receive this property from first_name key. * @ReceiveFrom("first_name") */ public $firstname; }
现在,尝试转换数据。
namespace MyApp; use kirillbdev\PhpDataTransformer\DataTransformer; use kirillbdev\PhpDataTransformer\DataObject\ArrayDataObject; use MyApp\Dto\UserDto; $dto = DataTransformer::transform(UserDto::class, new ArrayDataObject([ 'id' => 1, 'first_name' => 'Jon' // Custom key that differ of our DTO property. ]));
3. 类型转换
您可以为 DTO 中的特定属性指定想要转换的类型。使用 @Cast("type")
注解来做到这一点。目前,该包支持以下类型:int、float、bool。
namespace MyApp\Dto; class UserDto { /** * We want to cast this property to integer. * @Cast("int") */ public $id; }
您还可以将属性转换为其他类型化对象。为此,您可以使用 @Cast(<classname>)
注解。我建议您使用包含命名空间的全类名。
namespace MyApp\Dto; class UserDto { /** * We want to cast this property to UserRoleDto. * @Cast(<MyApp\Dto\UserRole>) */ public $role; }
4. 自定义转换逻辑
有时需要实现所需属性的自定义转换逻辑。在这种情况下,您可以为所需属性实现任意转换方法。该方法必须命名为 transform{PropertyName}Property
,并接受一个参数 DataObjectInterface
,该参数用于检索数据。
namespace MyApp\Dto; use kirillbdev\PhpDataTransformer\Contracts\DataObjectInterface; class UserDto { public $id; /** * We need to receive this property as combination of two keys (firstname and lastname). */ public $fullName; /** * Let's implement custom transformation method. * * @param DataObjectInterface $dataObject * @return string|null */ public function transformFullNameProperty(DataObjectInterface $dataObject) { return $dataObject->get('firstname') . ' ' . $dataObject->get('lastname'); } }