pfazzi/simplex-mapper

一个简单的映射库

0.0.6 2022-01-06 16:27 UTC

This package is auto-updated.

Last update: 2024-09-07 14:47:28 UTC


README

一个简单的PHP库,用于将源数据(对象或数组)传输到对象。

$dbData = [
    'username' => 'pfazzi',
    'emailAddress' => 'pfazzi@test.com',
    'isEnabled' => '1',
];

$mapper = new \Pfazzi\SimplexMapper\Mapper();

$user = $mapper->map(
    source: $dbData, 
    target: User::class, 
);

您在寻找一种简单的方法将数组转换为对象吗?
您想将DTO映射到领域对象吗?
您想从数组中填充对象吗?
使用SimplexMapper!

特性

  • 易于使用
  • 零配置
  • 零依赖
  • 支持PHP 8联合类型
  • 支持嵌套对象
  • 使用反射,无需修改您的对象

安装

使用composer安装SimplexMapper

composer require pfazzi/simplex-mapper

用法

映射

将源数据映射到目标类的新实例

$mapper = new \Pfazzi\SimplexMapper\Mapper();

// From Array 

$userEntity = $mapper->map(source: ['name' => 'patrick'], target: UserEntity::class);

// From stdClass 

$rawData = new \stdClass();
$rawData->name = 'Patrick';

$userEntity = $mapper->map(source: $rawData, target: UserEntity::class);

// From anonymous class

$rawData = new class {
    public function __construct(private string $name = 'Patrick') {}
};

$userEntity = $mapper->map(source: $rawData, target: UserEntity::class);

// From object

$rawData = new UserDto('Patrick');

$userEntity = $mapper->map(source: $rawData, target: UserEntity::class);

填充

使用源数据填充对象实例

$mapper = new \Pfazzi\SimplexMapper\Mapper();

$userEntity = $entityManager->find(UserEntity::class, 1);

// From Array 

$mapper->hydrate(source: ['name' => 'patrick'], target: $userEntity);

// From stdClass 

$rawData = new \stdClass();
$rawData->name = 'Patrick';

$mapper->map(source: $rawData, target: $userEntity);

// From anonymous class

$rawData = new class {
    public function __construct(private string $name = 'Patrick') {}
};

$mapper->map(source: $rawData, target: $userEntity);

// From object

$rawData = new UserDto('Patrick');

$mapper->map(source: $rawData, target: $userEntity);

用例

将数据库数据映射到读取模型

您想使用Doctrine DBAL连接从供应商表读取数据并实例化一个供应商读取模型吗?

class Supplier
{
    public function __construct(
        public int $id,
        public string $taxId,
        public bool $onConsignment,
    ) {
    }
}

$result = $connection->executeQuery(<<<'SQL'
    SELECT
        supplier.id,
        supplier.tax_id AS taxId,
        supplier.is_enabled AS isEnabled
    FROM supplier
    WHERE supplier.tax_id = :taxId
SQL, ['taxId' => $taxId]);

$data = $result->fetchAssociative();

没有SimplexMapper,您必须编写映射代码,例如:

$readModel = new Supplier(
    (int) $data['id'],
    $data['taxId'],
    '1' == $data['isEnabled'],
);

使用SimplexMapper,您只需要编写以下一行代码

$readModel = $this->mapper->map($data, Supplier::class);