command実行できるアプリケーションをLaravelで作る方法
- artisanコマンドでCommandクラス作成
- routes/console.php内に記述
背景
業務でphpファイルをコマンド実行することがありましたので復習の為にまとめます。
今回はLaravel Sailを使用します。SailはアプリケーションのDockerコンテナ内でArtisanコマンドを実行します。
以下が今回の勉強の為に作ったリポジトリです。
以下参考に進めます。
Commandクラスとは
コマンド実行後に呼び出されるクラスです、コマンド実行時に行いたい処理を記述できます。
Commandクラスを作成する
./vendor bin sail
をsail
に省略しています。
sail artisan make:command SampleCommand
INFO Console command [app/Console/Commands/SampleCommand.php] created successfully.
以下のファイルが作成されます。
example-app/app/Console/Commands/SampleCommand.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SampleCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:sample-command';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle()
{
//
}
}
Commandクラスの構成
signatureプロパティ
command名を決める為に使用されます。
descriptionプロパティ
コンソール画面に表示する為に使用されます。
handleメソッド
コマンドが実行されると呼び出されます。
ここにロジックを書きます。
command実行をしてみる
呼び出されている事を確認する為にhandleメソッドを以下のように修正します。
example-app/app/Console/Commands/SampleCommand.php
public function handle()
{
$this->info('handle method is calld');
}
infoメソッドは文字列をコンソールに出力してくれるメソッドです。
sail artisan app:sample-command
handle method is called
実行すると呼び出されていることが確認できました。
routes/console.phpで簡単にコマンドを定義する
example-app/routes/console.php
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote')->hourly();
このファイルでもコマンドを定義できます。
以下を追記します。
example-app/routes/console.php
Artisan::command('easy-command', function () {
$this->info('This is an easy command');
});
コマンド実行します。
sail artisan easy-command
This is an easy command
最後に
- 概要は掴めました
- 次回はEloquentモデルをコマンド実行で操作します
- 業務でブラウザ通知の処理をコマンドで実行していたのでそれも作ってみます
- スケジュール実行する機能についても勉強したいです
参考