tibisoft/autotransformer

一个将 DTO 转换为实体以及反向转换的小工具

0.7.0 2024-05-31 18:46 UTC

This package is auto-updated.

Last update: 2024-10-01 00:07:49 UTC


README

Autotransformer 是一个小工具,它执行基本的 DTO 到实体的转换以及反向转换。

安装

composer require tibisoft/autotransformer

使用方法

无需任何额外配置,转换器将遍历目标类/对象的属性,并尝试在源中找到同名属性。

class User {
    public function __construct(
        private string $email,
        private string $plainPassword,
        private int $age,
    ) {
    
    }
}

class UserDTO {
    public function __construct(
        private string $email,
        private int $age,
    ) {
    
    }
}

$user = new User('example@email.com', 'someSecretPassword', 25);

$transformer = new \Tibisoft\AutoTransformer\AutoTransformer();
$userDTO = $transformer->transform($user, UserDTO::class);

//output:
object(UserDTO)#8 (2) {
  ["email":"UserDTO":private]=>
  string(17) "example@email.com"
  ["age":"UserDTO":private]=>
  int(25)
}

转换操作

如果默认的转换过程不够用,您可以为目标对象/类添加属性并自定义输出。

同义词

class User {
    public function __construct(
        private string $email,
        private string $plainPassword,
        private int $age,
    ) {
    
    }
}

class UserDTO {
    public function __construct(
        private string $email, 
        #[\Tibisoft\AutoTransformer\Attribute\Synonyms(['age'])] 
        private int $yearsLive,
    ) {
    
    }
}

$user = new User('example@email.com', 'someSecretPassword', 25);

$transformer = new \Tibisoft\AutoTransformer\AutoTransformer();
$userDTO = $transformer->transform($user, UserDTO::class);

//output:
object(UserDTO)#8 (2) {
  ["email":"UserDTO":private]=>
  string(17) "example@email.com"
  ["yearsLive":"UserDTO":private]=>
  int(25)
}

计数

class User {
    public function __construct(
        private string $email, 
        private array $comments,
    ) {
    
    }
}

class UserDTO {
    public function __construct(
        private string $email,
        #[\Tibisoft\AutoTransformer\Attribute\Count]
        private int $comments,
    ) {
    
    }
}

$user = new User('example@email.com', ['Comment #1', 'Comment #2', 'Comment #3', 'Comment #4']);

$transformer = new \Tibisoft\AutoTransformer\AutoTransformer();
$userDTO = $transformer->transform($user, UserDTO::class);

//output:
object(UserDTO)#8 (2) {
  ["email":"UserDTO":private]=>
  string(17) "example@email.com"
  ["comments":"UserDTO":private]=>
  int(4)
}

是否在数组中

class InArrayClass
{
    public function __construct(
        public array $roles = [],
    ) {

    }
}

class InArrayDTO
{
    public function __construct(
        #[\Tibisoft\AutoTransformer\Attribute\InArray(property: 'roles', value: 'ROLE_TEAMLEADER')]
        public bool $isTeamleader,
    ) {

    }
}

$object = new InArrayClass(['ROLE_USER', 'ROLE_TEAMLEADER']);

$transformer = new \Tibisoft\AutoTransformer\AutoTransformer();
$inArrayDTO = $transformer->transform($object, InArrayDTO::class);

//output:
object(InArrayDTO)#8 (1) {
  ["isTeamleader"]=>
  bool(true)
}