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

Laravel框架
458
0
0
2022-04-12

简介

返回值一般采用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';}
}