laravel 建立自定义的artisan make命令

前言

咱们在laravel开发时常常用到artisan make等命令来新建ControllerModelJobEvent等类文件。 在Laravel5.2artisan make命令支持建立以下文件:php

make:auth           Scaffold basic login and registration views and routes
  make:console        Create a new Artisan command
  make:controller     Create a new controller class
  make:event          Create a new event class
  make:job            Create a new job class
  make:listener       Create a new event listener class
  make:middleware     Create a new middleware class
  make:migration      Create a new migration file
  make:model          Create a new Eloquent model class
  make:policy         Create a new policy class
  make:provider       Create a new service provider class
  make:request        Create a new form request class
  make:seeder         Create a new seeder class
  make:test           Create a new test class
复制代码

不过,有时候默认的并不可以知足咱们的需求, 比方咱们在项目中使用的Respository模式来进一步封装了Model文件,就须要常常建立Repository类文件了,时间长了就会想能不能经过artisan make:repository命令自动建立类文件而不是都每次手动建立。laravel

系统自带的artisan make命令对应的PHP程序放在Illuminate\Foundation\Console目录下,咱们参照Illuminate\Foundation\Console\ProviderMakeCommand类来定义本身的artisan make:repository命令。app

建立命令类

app\Console\Commands文件夹下建立RepositoryMakeCommand.php文件,具体程序以下:ide

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) {
        return $rootNamespace.'\Repositories';
    }
}
复制代码

建立命令类对应的模版文件

app\Console\Commands\stubs下建立模版文件 .stub文件是make命令生成的类文件的模版,用来定义要生成的类文件的通用部分 建立repository.stub模版文件:this

namespace DummyNamespace;
    
    use App\Repositories\BaseRepository;
    
    class DummyClass extends BaseRepository {
        
        /** * Specify Model class name * * @return string */
        public function model() {
            //set model name in here, this is necessary!
        }
    }
复制代码

注册命令类

将RepositoryMakeCommand添加到App\Console\Kernel.phpspa

protected $commands = [
        Commands\RepositoryMakeCommand::class
    ];
复制代码

使用命令

好了, 如今就能够经过make:repository命令来建立repository类文件了code

php artisan make:repository TestRepository

php artisan make:repository SubDirectory/TestRepository 
复制代码
相关文章
相关标签/搜索