使用简单工厂的 DTO

1.1.11 2023-06-23 11:56 UTC

This package is auto-updated.

Last update: 2024-09-23 14:54:53 UTC


README

Latest Version on Packagist Total Downloads

简单创建从任何数组来的 DTO。

安装

####需求

  • PHP 8.0
  • Laravel 8 | 9

您可以通过 composer 安装此包

composer require bpartner/dto

用法

声明您的 DTO 对象。您可以使用任何类型声明。

对于数组或集合,您可以使用 PHPDoc 注释中的数据类型。仅支持数组和集合。

class DemoDto extends DtoAbstract
{
    //Optional
    protected const CLASS_FORM_REQUEST = UpdateUserFormRequest::class;
    
    /**
    * DTO fields
    */
    public string $name;
    public Carbon $date;
    public DtoOtherObject $otherObject;
    
    /** @var collection<\App\Dto\DtoOtherObject>  */
    public Collection $objectsCollection;
    
    /** @var array<\App\Dto\DtoOtherObject>  */
    public array $objectsArray;
    
    /** @var collection<\App\Dto\DtoOtherObject>  */
    public array $objectsArrayOfCollection;
    }

通过 facade Dto 从任何数组数据(例如:request()->all())创建 DTO

//In any place of your code
$data = request()->all(); //array data
$dto = Dto::build(DemoDto::class, $data);

或从 FormRequest

/**
 * In controller
 * 
 * Create FormRequest and assign to CLASS_FORM_REQUEST const in DTO
 * 
 */ 
public function store(DemoDto $dto)
{
    //Use $dto made from UpdateUserFormRequest
}

现在您可以将您的 DTO 作为参数传递给任何对象并使用它

$name = $dto->name;
$objectCollection = $dto->objectsCollection;

您可以通过第三个参数将输入参数转换为任何字符串格式。(例如:first_name -> firstName)

class DemoDto extends DtoAbstract
{
    public string $firstName;
}

$inputData = [
    'first_name' => 'John Doe'
];

$dto = Dto::build(DemoDto::class, $inputData, DtoFactory::CAMEL_CASE);

自定义映射

您可以使用自定义映射创建 DTO。添加静态方法 withMap()

public static function withMap(array $data): DtoInterface
{
    $mappedData = [
        'dto_param' => $data['some_param'],
    ];
    
    return new static($mappedData);
}

//Client code
$dto = Dto::build(DemoDto::class, request()->all());

将您的 DTO 转换为数组或扁平数组。

$array = $dto->toArray();

array:4 [
  "name" => "Demo data"
  "date" => "06-11-2021"
  "phone" => array:2 [
    "type" => "home"
    "number" => "500-123-123"
  ]
  "phones" => array:2 [
    0 => array:2 [
      "type" => "work"
      "number" => "500-123-122"
    ]
    1 => array:2 [
      "type" => "private"
      "number" => "500-123-124"
    ]
  ]
]

$flat = $dto->flatArray();

array:5 [                       
  "name" => "Demo data"         
  "date" => "06-11-2021"        
  "type" => "home"              
  "number" => "500-123-123"     
  "phones" => array:2 [         
    0 => array:2 [              
      "type" => "work"          
      "number" => "500-123-122" 
    ]                           
    1 => array:2 [              
      "type" => "private"       
      "number" => "500-123-124" 
    ]                           
  ]                             
]                               

重要!集合和嵌套数组不能转换为扁平数组。

鸣谢

许可证

MIT 许可证(MIT)。请参阅许可证文件以获取更多信息。