閱讀LC教程的第三本,手動建立Transformer比較麻煩,參照Laravel的原始碼,自己寫了個,如下:
- 命令列執行
php artisan make:command TransformerMakeCommand
生成TransformerMakeCommand.php
檔案,當中程式碼如下:
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
class TransformerMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:transformer';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new transformer class';
/**
* The type of class being generated.
*
* @var string
*/
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';
}
}
- 在下面圖片所示目錄中建立模版檔案
transformer.stub 中的程式碼如下:
<?php
namespace DummyNamespace;
use League\Fractal\TransformerAbstract;
class DummyClass extends TransformerAbstract
{
public function transform()
{
return [
];
}
}
- 命令列
php artisan make:transformer TestTransformer
, 成功
本作品採用《CC 協議》,轉載必須註明作者和本文連結