Laravelでバッチ処理を作成する
コンソールからコマンドでバッチ処理のファイルを作成する
php artisan make:command MyBatchCommand
コマンドを実行すると、app/Console/Commands/MyBatchCommand.phpというファイルが生成されます。内容は下記のようになっています。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class MyBatchCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command:name';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
return Command::SUCCESS;
}
}
作成したファイルに処理を記述する
// testというコマンド名にする場合
protected $signature = 'command:test';
→ 実行する際のコマンド名になります。command:testなどバッチ処理名を記述しましょう。
引数ありのバッチ処理にする
引数を設定する場合には、
// 引数を1つ設定する
protected $signature = 'command:test {arg0}';
というように、signatureに引数を受けるように記述します。{arg0?}
のように?をつければ省略可能な引数として設定できます。
また、{arg0=1}
とするとデフォルト値は1であると定義も可能です。
引数の受け取り方は以下のような感じ。
public function handle()
{
// 引数を$arg0に格納
$arg0= $this->argument('arg0');
}
引数ありのバッチ実行
php artisan command:test hoge
オプションありのバッチ処理にする
その他、{--option}
という値を必要としないオプションや、{--option=}
という値有りのオプションも定義ができます。
引数の受け取り方は以下のような感じ。
public function handle()
{
// 値なしオプション、指定があるかどうかで処理を分岐
if ( $this->option('option') ) { }
// 値ありオプション、値を格納
$op = $this->option('option');
}
オプションありのバッチ実行
# 値なし
php artisan command:test --option
# 値あり
php artisan command:test --option=foo