簡介
返回值一般採用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 協議》,轉載必須註明作者和本文連結