编写 PHP artisan make:transformer 命令方便生成 Tranformers

阅读LC教程的第三本,手动创建Transformer比较麻烦,参照Laravel的源码,自己写了个,如下:

  1. 命令行执行 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';
     }
}
  1. 在下面图片所示目录中创建模版文件

file

transformer.stub 中的代码如下:

<?php

namespace DummyNamespace;

use League\Fractal\TransformerAbstract;

class DummyClass extends TransformerAbstract
{
    public function transform()
    {
        return [

        ];
    }
}
  1. 命令行 php artisan make:transformer TestTransformer, 成功

file

原文地址:https://laravel-china.org/articles/10309/read-lc-tutorial-third-write-php-artisan-maketransformer-command-to-facilitate-the-production-of-tranformers

posted @ 2018-04-25 12:27  花泪哲  阅读(769)  评论(0)    收藏  举报