咱們在laravel
開發時常常用到artisan make:controller
等命令來新建Controller
、Model
、Job
、Event
等類文件。 在Laravel5.2
中artisan 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
命令。segmentfault
在app\Console\Commands
文件夾下建立RepositoryMakeCommand.php文件,具體程序以下:app
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
模版文件:ide
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.php
中測試
protected $commands = [ Commands\RepositoryMakeCommand::class ];
好了, 如今就能夠經過make:repository命令來建立repository類文件了this
php artisan make:repository TestRepository php artisan make:repository SubDirectory/TestRepository