咱们在laravel
开发时常常用到artisan make
等命令来新建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
命令。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.php
中spa
protected $commands = [
Commands\RepositoryMakeCommand::class
];
复制代码
好了, 如今就能够经过make:repository命令来建立repository类文件了code
php artisan make:repository TestRepository
php artisan make:repository SubDirectory/TestRepository
复制代码