etshy/automapper

PHP 的 Automapper

1.2 2023-06-05 23:37 UTC

This package is auto-updated.

Last update: 2024-09-06 02:53:18 UTC


README

pipeline status coverage report

这是一个轻量级库,可以快速将一个对象或数组映射到另一个对象上,深受 Automapper-plus 的启发。希望它能满足您的所有用例。

此库不使用任何反射!

安装

composer require etshy/automapper

symfony 的未来包在这里

使用方法

以下是如何配置映射的示例

<?php

use Etshy\AutoMapper\Configuration\AutoMapperConfiguration;
use Etshy\AutoMapper\AutoMapper;

$config = new AutoMapperConfiguration();

$config
    ->registerMapping(Source::class, Target::class) // -> this is enough if Source and Target have the same property name
    ->forMember('updatedAt', function (Source $source) { // -> use callback function or PropertyMapper on the forMember method
        return $source->getCreatedAt();
    });
                            
$mapper = new AutoMapper($config);

$source = new Source();
$target = $mapper->map($source, Target::class);
// $mapper->mapToObject(source,target); -> use mapToObject() to map to an existing object
// $mapper->mapMultiple([$source],Target::class); -> use mapMultiple to map an iterable of source 

echo $target->getUpdatedAt();

属性映射器

PropertyMapper 用于自定义映射

FromCallable

PropertyMapper::fromCallable(function($souce) {})

等同于直接使用回调。

FromProperty

Propertymapper::fromProperty('propName')

定义从哪个属性获取数据

ToClass

PropertyMapper::toClass($targetClass, $sourceIsObjectArray)

定义一个类来映射属性,如果您有嵌套类则很有用。您将需要为子类注册映射。

Ignore

PropertyMapper::ignore()

简单地忽略目标属性

选项

IgnoreNullProperties/dontIgnoreNullProperties

$mapping = $this->config->registerMapping(Source::class, Target::class);
$mapping->getOptions()->ignoreNullProperties();

此选项将忽略源中的 null 属性。特别适用于与 mapToObject 一起使用,但如果目标类中存在默认值,也可能很有用。

setPropertyWriter/setPropertyReader

$mapping = $this->config->registerMapping(Source::class, Target::class);
$mapping->getOptions()->setPropertyWriter(new SwaggerModelPropertyAccessor());

如果您想使用除默认之外的其他 PropertyReaderPropertyWriter,则此选项很有用(ObjectPropertyAccessorArrayPropertyAccessor)。我为 Swagger 生成的模型提供了一个 SwaggerModelPropertyAccessor

这就是现在的全部内容。希望这个轻量级库能帮到您!