Laravelでバッチ処理を書いた時のメモ
■artisanに登録する
app/start/artisan.php
artisan.php
Artisan::add(new \commands\TestCommand());
■処理を記述
app/commands/TestCommand.phpに処理を記述
・Illuminate\Console\Commandを継承する
・fire()にメイン処理を記述する
・getArguments()に引数の設定を記述
・getOptions()にオプションの設定を記述
TestCommand.php
namespace commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use models\batch\BatchTestModel;
class TestCommand extends Command
{
protected $name = 'batch:test';
protected $description = 'アーティザンのテスト';
public function fire()
{
// 全ての引数を取得する
$argument = $this->argument();
// 引数を全て表示してみる
$this->info(json_encode($argument));
// Modelを呼び出してみる
$exec = new BatchTestModel();
$exec->execute($argument());
}
/**
* 受け取る引数の設定
* @return array
*/
protected function getArguments()
{
return [
['argument1', InputArgument::REQUIRED, '引数の説明・・・必須'],
['argument2', InputArgument::OPTIONAL, '引数の説明・・・任意']
];
}
/**
* 受け取るオプションの設定
* @return array
*/
protected function getOptions()
{
return [
['example1', 'e', InputOption::VALUE_REQUIRED, 'オプションの説明・・・必須'],
['example2', 'f', InputOption::VALUE_OPTIONAL, 'オプションの説明・・・任意']
];
}
}
■artisanコマンドで処理を実行する
$ php artisan batch:test --example1 option1 -f option2 value1 value2
{"command":"batch:test","argument1":"value1","argument2":"value2"}
["option1","option2"]
------おまけ------
■使用できるartisanコマンドの一覧を表示してみる
TestCommand.phpの
・protected $name
・protected $description
で設定した内容が一覧表示される。
$ php artisan list
・・・省略
batch
batch:test アーティザンのテスト
■ヘルプを表示
helpコマンド打つとTestCommand.phpの内容を読み取り使用方法が出力される
$ php artisan batch:test --help
Usage:
batch:test [-e|--example1="..."] [-f|--example2[="..."]] argument1 [argument2]
Arguments:
argument1 引数の説明・・・必須
argument2 引数の説明・・・任意
Options:
--example1 (-e) オプションの説明・・・必須
--example2 (-f) オプションの説明・・・任意
--help (-h) Display this help message.
・・・以下省略