onmoon/dto-mapper

将任何数组或类树映射到DTO的类

1.3.1 2023-01-25 12:28 UTC

This package is auto-updated.

Last update: 2024-08-25 16:03:26 UTC


README

关于

此类帮助将任何类或关联数组树映射到DTO类树。

它使用反射来创建DTO,但调用getter或读取属性从源树获取值,并且只有DTO中找到的属性将从源对象中获取。这使得映射器在例如 doctrine 懒加载时工作良好。

对于对象 object 如果需要键属性 property,将检查以下来源

  • object->propery
  • object[property]
  • object->getPropery()
  • object->isPropery()
  • object->hasPropery()
  • object->propery()
  • object->__call('property')

所有方法调用都是不区分大小写的。

DTO必须为其所有属性指定类型,并且所有数组属性都应具有指定项目类型的phpDoc。

安装

安装此扩展的首选方式是通过composer

运行

composer require onmoon/dto-mapper

使用

public function showPetById(int $petId) : ShowPetByIdResponseDto
{
    $pet   = $this->pets->getById($petId);

    $mapper = new OnMoon\DtoMapper\DtoMapper();
    return $mapper->map($pet, ShowPetByIdResponseDto::class);
}

DateTime处理

DateTime类不支持通过反射创建。如果DTO属性是DateTimeInterface的子类,则此属性设置为新的\Safe\DateTime实例。对于DateTime的源值可以是DateTimeInterface

重写源属性

默认情况下,映射器在源中搜索与DTO中相同的属性。如果您想从另一个源属性读取某些属性的值,可以将可调用对象作为第三个参数传递。此可调用对象应始终返回映射属性名称。

$mapper->map($pet, ShowPetByIdResponseDto::class, function ($propertyName, $context) { 
    $fullName = implode('->', [...$context, $propertyName]);
    if ($fullName === 'subObject->s2->property1') {
       return 'realProperty1';
    }
    return $propertyName;
});