arifseft/transformer

Laravel 模型转换器,适用于基于 API 的应用程序,具有关系。

v1.1.2 2020-07-18 09:46 UTC

This package is auto-updated.

Last update: 2024-09-18 19:25:42 UTC


README

使用 Laravel Eloquent 模型将指定键的数组转换为模型,可以选择将嵌套关系作为转换后的模型数组包含在内。

原因

创建此包是为了简化复杂性,简化模型,同时允许它们快速转换为指定键的数组。

但是将 Eloquent 模型转换为数组很容易吗?你只需要调用 toArray() 方法。当你想要最终数组只包含特定字段/键以及嵌套关系时,就会出现不足。你最终需要在控制器中转换模型,指定数组中每个键和值的每个键和值。

示例

没有 Laravel 模型转换器

$user = App\User::with('school')->first();

$data = $user->toArray();

/**
 * What we get from the broad example is something like:
 *   [
 *      'id' => 1,
 *       'email' => 'example@example.com',
 *       'password' => '.....',
 *       'first_name' => 'John',
 *       'last_name' => 'Doe',
 *       'school_id' => 1,
 *       'created_at' => '...',
 *       'updated_at' => '...',
 *       'school' => [
 *           'id' => 1,
 *           'name' => 'Example University',
 *           'book_price' => 6000,
 *           'created_at' => '...',
 *           'updated_at' => '...'
 *       ]
 *   ];
 */

使用 Laravel 模型转换器

$user = App\User::first();
$user->transformer()->with('school')->transform();

并返回

[
    'id' => 1,
    'email' => 'example@example.com',
    'name' => 'John Doe',
    'school' => [
        'id' => 1,
        'name' => 'Example University'
    ]
]

入门

以下说明将帮助您启动并使用 Laravel 应用程序中的包。

先决条件

该包是在 Laravel 5.2 和 PHP 7 上开发的,因此可能与 PHP 5 不兼容。

- PHP >= 7
- Laravel >= 5.2

安装

要在 Laravel 应用程序中安装此包,请按照以下步骤操作。

步骤 1:从项目根目录运行以下命令。

composer require erikgall/transformer

步骤 2:将包的服务提供者添加到 app.php 配置文件中的提供者数组。

EGALL\Transformer\TransformerServiceProvider::class

步骤 3:在您的模型文件所在目录中创建一个 transformers 目录。例如,使用用户模型及其转换器类的位置

- app/User.php -> app/transformers/UserTransformer.php
- app/Models/User.php -> app/models/transformers/UserTransformer.php

* The Transformers directory must be in the same directory as you models... Only if you wish to use the automatic transformer class finder. Otherwise you must specify the model's transformer class/full namespace.

步骤 4:任何想要使用转换器的模型都必须实现 EGALL\Transformer\Contracts\Transformable 接口/契约。您还应该在您的模型类中包含 EGALL\Transformer\Traits\TransformableModel 特性。

namespace App;

use App\Transformers\UserTransformer;
use Illuminate\Database\Eloquent\Model;
use EGALL\Transformer\Contracts\Transformable;
use EGALL\Transformer\Traits\TransformableModel;

class User extends Model implements Transformable {

    use TransformableModel;

    // Only use if your Transformer directory does not sit in the same directory
    // as the model file.
    // protected $transformer = 'Acme\Transformers\UserTransformer';

    // Used in example below
    public function school()
    {

        return $this->belongsTo(School::class);

    }

}

以下示例

用户模型转换器类

namespace App\Transformers;

use EGALL\Transformer\Transformer;

class UserTransformer extends Transformer {

    protected $keys = ['id', 'name', 'address'];

    // Create a custom attribute getter method like you would
    // in an eloquent model using the syntax get`AttributeName`Attrbute.
    public function getNameAttribute()
    {

        return $this->model->first_name . ' ' . $this->model->last_name;

    }

}

从控制器中使用用户模型转换器。

namespace App\Http\Controllers;

use Guard;

class UserController extends Controller {

    protected $user;

    public function __construct(Guard $guard)
    {

        $this->user = $guard->user();

    }

    public function me()
    {

        // Get only the user transformer data
        $data = $this->user->transform();

        // return an array with a transformed relationship.
        // if the relationship does not implement the transformable class
        // the transformer will call the toArray() on the model.
        $data = $this->user->transformer()->with('course')->transform();

    }

    public function dependencyInjectionExample(\EGALL\Transformer\Contracts\CollectionTransfomer $transformer)
    {

        // Collection example
        $transformer->collection(User::all())->keys('id', 'name')->with('school')->transform();

    }

    public function diExampleTwo(\EGALL\Transformer\Contracts\Transformer $transformer)
    {

        return $transformer->item($this->user)->keys(['id', 'first_name', 'last_name])->transform();

    }

}

运行测试

安装包及其依赖项。完成后,进入包的根目录,运行以下命令

vendor/bin/phpunit

构建所用/使用

  • Laravel
  • PHPUnit
  • PhpStorm

贡献

请阅读 CONTRIBUTING.md 以了解我们的行为准则和向我们提交拉取请求的过程。

版本控制

我们使用 SemVer 进行版本控制。有关可用版本,请参阅此存储库的 标签

作者

许可证

本项目采用 MIT 许可证 - 有关详细信息,请参阅 LICENSE.md 文件