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

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

一 创建命令类

在vendor\laravel\framework\src\Illuminate\Foundation\Console目录下记录着artisan make命令对应的php文件,比如说经常使用的make:model命令对应的ModelMakeCommand.php文件.但是在这里我们将仿照ProviderMakeCommand.php文件自定义我们的repository命令:

1.创建Command目录
在app\Console目录下新建Commands目录

2.创建RepositoryMakeCommand.php文件,并添加命令执行的内容
在app\Console\Command目录下,新建RepositoryMakeCommand.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\Command目录下,新建stubs目录

2.创建模板文件repository.stub并添加模板
在app\Console\Command\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.的反馈时,就说明我们的配置没有问题了!

猜你喜欢

转载自www.cnblogs.com/MrBear/p/10146905.html