从零开始系列-Laravel编写api服务接口:10.transformer

简介

返回值一般采用dingo的 transformer,新版用source的方法。
只要定义好模型关联之后就可以用include自由包含所需要的对象(数组)了

include全部采用驼峰法命名!否则会出大问题!

如果是单个对象则用$this->response->item($obj, new xxxTransformer())

多个对象包含用$this->response->collection($objs, new xxxTransformer())

可以编写命令文件生成transformer

1.新建 app/Console/Commands/stubs/transformer.stub

<?php

namespace DummyNamespace;

use League\Fractal\TransformerAbstract;

class DummyClass extends TransformerAbstract
{
    protected $availableIncludes = [];
    public function transform(Obj $obj)
    {
        return [

        ];
    }
}

2.新建命令文件

php artisan make:command MakeTransformer

<?php

namespace App\Console\Commands;


use Illuminate\Console\GeneratorCommand;

class MakeTransformer extends GeneratorCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $name = 'make:transformer';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'create a new transformer class';

    protected $type = 'Transformer';
    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return __DIR__.'/stubs/transformer.stub';
    }

    /**
     * Get the default namespace for the class.
     *
     * @param string $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Transformers';
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
编程两年半,喜欢ctrl(唱、跳、rap、篮球)
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!