定制 erikgall/transformer 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

erikgall/transformer

Composer 安装命令:

composer require erikgall/transformer

包简介

Laravel model transformers with relationships for API based applications.

README 文档

README

Transform Laravel Eloquent models into an array of specified keys with the option of including nested relationships as their transformed model array.

The Reason

This package was created to ease complexity, simplify model's, while allowing for them to be quickly transposed into an array of specified keys.

But turning an eloquent model into an array is easy right? You only have to call the toArray() method. The shortfall comes when you want the final array to only have specific fields/keys, as well as a nested relationship. You end up transforming the model inside of your controller, specifying each and every key and value the array should have.

Example

Without Laravel Model Transformer

$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' => '...'
 *       ]
 *   ];
 */

With Laravel Model Transformer

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

And it returns:

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

Getting Started

These instructions will get you get you up and running and using the package inside of your Laravel application.

Prerequisities

The package was developed using Laravel 5.2 and PHP 7 so there may be incompatibilities with PHP 5.

- PHP >= 7
- Laravel >= 5.2

Installing

To install the package inside of your Laravel app, please follow the steps below.

Step 1: Run the following command from your project root.

composer require erikgall/transformer

Step 2: Add the package's service provider to your provider's array in you app.php config file.

EGALL\Transformer\TransformerServiceProvider::class

Step 3: Create a transformers directory inside of the directory where your model files live. Example using the location of a User model and its transformer class:

- 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.

Step 4: Any models use wish to use a transformer with must implement the EGALL\Transformer\Contracts\Transformable interface/contract. You should also include the trait EGALL\Transformer\Traits\TransformableModel inside of your model classes.

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);

    }

}

Example below:

User Model Transformer 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;

    }

}

Using the User Model Transformer from a controller.

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();

    }

}

Running the tests

Install the package and install it's dependencies. After, that is complete and once inside the package's root, run the following command:

vendor/bin/phpunit

Built With/Using

  • Laravel
  • PHPUnit
  • PhpStorm

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

License

This project is licensed under the MIT License - see the LICENSE.md file for details

erikgall/transformer 适用场景与选型建议

erikgall/transformer 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 306 次下载、GitHub Stars 达 6, 最近一次更新时间为 2016 年 07 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「json」 「api」 「model」 「laravel」 「transformer」 「eloquent」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 erikgall/transformer 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 erikgall/transformer 我们能提供哪些服务?
定制开发 / 二次开发

基于 erikgall/transformer 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 306
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 6
  • 点击次数: 8
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 6
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2016-07-05