Laravelにはコンソールアプリケーションの実装をサポートするCommandと呼ばれるコンポーネントがあります。
簡単にいうとartisanコマンドを自作することができるようになります。
Commandを実装するためにはクロージャーで実装する方法とCommandクラスを実装する方法があります。
実装方法
今回はクロージャーによる実装を紹介します。
クロージャはroutue/console.phpに実装します。
Artisan::command( ‘コマンド名’, function( ){ 実行時に処理されるクロージャ } )という形で指定します。
今回はcommentメソッドを使って文字列を出力しています。
Artisan::command('hello:clousure',function(){
$this->comment('Hello clousure command'); //文字列出力
})->describe('sample command'); //コマンド説明
コマンド名に「:」を含めることでその左側がグループ化されるので、helloグループの中にhello:clousureコマンドが表示されることが確認できます。
またコマンドの説明が出ていることがわかります。
php artisan list
(中略)
hello
hello:clousure sample command
(中略)
結果
Commandはartisanコマンドのサブコマンドとして実行します。
hello:clousureコマンドとして実行するには以下のようにphp artisanに引数として渡します。
php artisan hello:clousure
//結果
Hello clousure command
今回使用したコード
https://github.com/kt5007/laravel-command/tree/feature/%231_clousure_command
参考文献
本
PHPフレームワーク Laravel Webアプリケーション開発 バージョン8.x対応
サイト
https://laravel.com/docs/6.x/artisan