mekhtievrs/laravel-hydrator

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

1.0 2023-11-22 15:36 UTC

This package is not auto-updated.

Last update: 2024-09-26 17:26:37 UTC


README

安装

composer require mekhtievrs/hydrator

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

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

用法

生成数据映射器

php artisan make:mapper MyCustomDataMapper

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

<?php

namespace App\Mappers;

use Mekhtievrs\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();