laravel 自定义artisan命令,新建repository等类文件

在工作中,有时我们需要定制化一些命令,例如构建repository层,会创建很多的repository文件,如果一一创建,每次都要书写命名空间太麻烦,可不可以自定义artisan命令呢,像创建Controller文件一样,省却书写固定的代码,还好laravel给我们提供了这样自定义的机制.

一 创建命令类

1.创建命令文件
在命令行中输入下面的命令,会在app\Console目录下新建Commands\Repository.php文件

php artisan make:command Repository

2.打开Repository.php文件,并添加命令执行的名字

<?php
namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

class RepositoryMakeCommand extends GeneratorCommand
{
    /**
     * The console command name.
     *添加命令的名字
     * @var string
     */
    protected $name = 'make:repository';

    /**
     * The console command description.
     *命令的描述
     * @var string
     */
    protected $description = 'Create a new repository class';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Repository';

    /**
     * Get the stub file for the generator.
     *执行命令后将创建内容的模板
     * @return string
     */
    protected function getStub()
    {
        return __DIR__.'/stubs/repository.stub';
    }

    /**
     * Get the default namespace for the class.
     *
     * @param string $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
    //注意保存的目录,我这里把Repository目录放在了Http下,可以根据自己的习惯自定义
        return $rootNamespace.'\Http\Repositories';
    }
}

二 创建命令类对应的模板

1.创建存放模板文件的目录stubs
在app\Console\Commands目录下,新建stubs目录

2.创建模板文件repository.stub并添加模板
在app\Console\Commands\stubs 目录下,新建repository.stub文件,并添加以下模板内容

<?php
namespace DummyNamespace;


class DummyClass
{

    /*
    *    将需要使用的Model通过构造函数实例化
    */
    public function __construct ()
    {

    }

}

三 注册命令类

将创建的RepositoryMakeCommand 添加到app\Console\Kernel.php中

 protected $commands = [
        // 创建生成repository文件的命令
        Commands\RepositoryMakeCommand::class
    ];

四 测试

以上就完成了命令类的自定义,下面就可以使用了

 php artisan make:repository UserRepository

当看到Repository created successfully.的反馈时,就说明我们的配置没有问题了!

posted @ 2018-12-20 01:08  MrBear  阅读(1829)  评论(0编辑  收藏  举报