digitalhq/hydrator

用于从数据数组和集合中映射和填充Laravel模型的数据包

dev-master 2021-08-22 21:10 UTC

This package is not auto-updated.

Last update: 2024-09-30 12:40:05 UTC


README

安装

composer require digitalhq/hydrator

安装包后,将服务提供者类添加到config/app.php文件中

'providers' => [
    Digitalhq\Hydrator\HydratorServiceProvider::class,
],

使用

生成数据映射器

php artisan make:mapper MyCustomDataMapper

之后,生成器会创建映射器类,例如

<?php

namespace App\Mappers;

use Digitalhq\Hydrator\DataMapperInterface;

class MyMapper implements DataMapperInterface
{

    public function transform(array $data) : array
    {
        return [
            // Map properties here
        ];
    }

}

数据映射

// Map data array
$data = ['id' => 1, 'name' => 'Test 1'];

$mapped_collection = hydrator($data)->with(new MyMapper)->hydrate();
// or 
$mapped_collection = hydrator($data, new MyMapper)->hydrate();

// Map array of data array
$data = [
    ['id' => 1, 'name' => 'Test 1'],
    ['id' => 2, 'name' => 'Test 2'],
];
$mapped_collection = hydrator($data)->with(new MyMapper)->hydrate();

将数据填充到模型中

// Map array of data array
$data = [
    ['id' => 1, 'name' => 'Test 1'],
    ['id' => 2, 'name' => 'Test 2'],
];
$mapped_collection = hydrator($data)->with(new MyMapper)->to(User::class)->hydrate();