これまた、5.5で登場した機能で今まで知らなかった機能がありました。
Laravelではウェブだけでなく、コマンドラインで実行できるプログラムの開発も対応しています。開発は非常に簡単で、以下を実行すると、
$ php artisan make:command CommandProgram
app/Console/Commands/CommandProgram.phpの雛形のファイルを作成してくれます。
そのプログラムの実行には、app/Console/Kernel.phpを編集して、$commandsに以下の14行目のように追加して登録します。
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
Commands\CommandProgram::class, //ここに新規のコマンドを入れる
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
}
登録されたら、artisanコマンドのリストに表示されます。
$ php artisan Available commands: ... command command:name Command description ...
というのが5.4までだったのですが、5.5からはもうこの手間はもうなくなりました。 app/Console/Commandsのディレクトリにファイルを作成すれば、Kernel.phpを編集しなくても自動的に登録してくれます。
どうしてこうなるかというと、5.5のKernel.phpを見てみましょう。
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands'); // ここが5.5から追加された行
require base_path('routes/console.php');
}
}
メソッドのcommands()に、新しい行(36行目)が追加されています。そして、その1行が自動登録を行ってくれるのです!
コマンドラインで実行するプログラムのほとんどは、クロンジョブでスケジュールして実行されるプログラムですが、ときどき、アップした画像のサイズを変えるとか、DBのある項目の値をすべて更新変するとか、のバッチジョブが必要になることあります。
そのようなときは、管理のために、app/Console/Tasksのディレクトリを作成して、クロンジョブのプログラムと分けます。そして、もちろんこれらの登録は、以下のようにして自動にすればよいです。今度は配列で引数を渡していることに注意を。
...
protected function commands()
{
$this->load([__DIR__.'/Commands', __DIR__.'/Tasks']); // ここが5.5から追加された行
require base_path('routes/console.php');
}
}
メルマガ購読の申し込みはこちらから。
