Laravel自定義command命令
用過Laravel
的都知道,Laravel
通過php artisan make:controller
可以生成控制器,同樣的夜可以用命令生成中間介和模型,那怎麼自定義生成檔案呢?
1.建立command類
<?php namespace App\Console\Commands; use Illuminate\Console\GeneratorCommand; class ServiceMakeCommand extends GeneratorCommand { /** * The console command name. * * @var string */ protected $name = 'make:service'; /** * The console command description. * * @var string */ protected $description = 'Create a new service class'; /** * The type of class being generated. * * @var string */ protected $type = 'Services'; /** * Get the stub file for the generator. * * @return string */ protected function getStub() { return __DIR__.'/stubs/service.stub'; } /** * Get the default namespace for the class. * * @paramstring$rootNamespace * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace."\Services"; } }
2.在Commands/stubs檔案下建立自定義模板檔案
<?php namespace DummyNamespace; class DummyClass { public function __construct() { } }
建立了一個只有建構函式的類,具體模板可以自己定義
執行測試
php artisan make:service Web/TestService
這個時候Services
檔案下的Web
目錄下會生成TestService
檔案,Web
目錄不存在時會自動建立