bigyohann/symfony-dto-bundle

此包已被废弃,不再维护。未建议替换包。

添加自动Dto转换器的Symfony扩展包

安装: 125

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 0

开放问题: 0

类型:symfony-bundle

2.0.1 2023-02-20 22:34 UTC

This package is auto-updated.

Last update: 2023-09-20 23:52:19 UTC


README

动机

  • 创建并部署一个lib到Packagist
  • 为Symfony创建一个扩展包
  • 简化序列化处理方式

使用方法

Bigyohann\DtoBundle\Dto\Dto 扩展您的Dto类,将所有属性设为私有,并添加getter。

默认情况下,我添加了一个转换函数,用于自动将Dto属性设置为传递给参数的对象。

您可以使用属性 Bigyohann\DtoBundle\Attributes\ConvertProperty 注释您的属性,如果参数 shouldConvertAutomatically 设置为false,则属性不会被映射到传递给参数的对象,但您仍可以在Dto中访问它,如果您想对此值执行特定操作。

如果您不想使用转换函数,您可以使用 Bigyohann\DtoBundle\Dto\DtoInterface

示例

use Bigyohann\DtoBundle\Attributes\ConvertProperty;
use Bigyohann\DtoBundle\Dto\Dto;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\Type;

class UserDto extends Dto
{
    #[ConvertProperty]
    #[Type(type: 'string')]
    #[Length(min: 2, max: 20)]
    private ?string $name;    
    
    #[ConvertProperty(shouldConvertAutomatically: false)]
    #[Type(type: 'string')]
    private ?string $password;

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

}

直接在Controller函数中注入Dto

    public function create(UserDto $dto){
        $user = new User();
        
        $dto->transformToObject($user);
        
        // password is not automatically convert in $user, do your custom logic with $dto->getPassword()
        // Add your custom logic here
    }