Laravel通過Artisan提供了強大的控制臺命令來處理非瀏覽器業務邏輯。
前言
本文主要跟大家介紹的是關于laravel通過創建自定義artisan make命令來新建類文件的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧。
我們在laravel開發時經常用到artisan make:controller等命令來新建Controller、Model、Job、Event等類文件。 在Laravel5.2中artisan make命令支持創建如下文件:
make:auth Scaffold basic login and registration views and routes make:console Create a new Artisan command make:controller Create a new controller html' target='_blank'>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命令自動創建類文件而不是都每次手動創建。
系統自帶的artisan make命令對應的PHP程序放在IlluminateFoundationConsole目錄下,我們參照IlluminateFoundationConsoleProviderMakeCommand類來定義自己的artisan make:repository命令。
一、創建命令類
在appConsoleCommands文件夾下創建RepositoryMakeCommand.php文件,具體程序如下:
namespace AppConsoleCommands;use IlluminateConsoleGeneratorCommand;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 }
二、創建命令類對應的模版文件
在appConsoleCommandsstubs下創建模版文件 .stub文件是make命令生成的類文件的模版,用來定義要生成的類文件的通用部分創建repository.stub模版文件:
namespace DummyNamespace; use AppRepositoriesBaseRepository; class DummyClass extends BaseRepository * Specify Model class name * @return string public function model() //set model name in here, this is necessary! }
三、注冊命令類
將RepositoryMakeCommand添加到AppConsoleKernel.php中
protected $commands = [ CommandsRepositoryMakeCommand::class ];
測試命令
好了, 現在就可以通過make:repository命令來創建repository類文件了
php artisan make:repository TestRepositoryphp artisan make:repository SubDirectory/TestRepository
以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP !
相關推薦:
關于Laravel中重寫資源路由自定義URL的實現方法
關于laravel 5.4中實現無限級分類的方法
以上就是如何通過laravel來創建自定義artisan make的命令新建類文件的詳細內容,PHP教程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答