symfony 1.4でタスク(task)を利用する時の注意
symfony 1.4.4でタスクを、アクションから利用する、もしくは、ほかのタスクから利用する時にハマったのでメモ。
symfonyでのタスクは、CUIでのsymfony利用を可能にします。バッチ処理の時に利用したりします。便利な機構で、引数も設定可能になっています。
また、タスクから別なタスクを呼び出すこと。action(アクション)からタスクを呼び出すことも可能です。
タスクには、引数として、$argumentsと、$optionsの二つがあります
arguments
引数として下記のように設定することができます。
下記のテストタスクで下記のように実行します
php symfony sample:test dev type1
すると
$arguments['env'] => dev $arguments['type'] => type1
となります
options
引数に似た形で、オプションがあります。
下記のテストタスクで下記のように実行します
php symfony sample:test --evn=dev --type=type1
すると
$options['env'] => dev $options['type'] => type1
となります
タスクから他のタスクを呼び出す
exec()を使って実行結果を受け取る方法もあるけれど、symfonyの機構としても用意されています。runTask()で実行が可能です。
第一引数は、タスクの名前で、第二引数は、$argumentsで、第三引数は$options。
ポイントは、実行したいタスクに$argumentsを用意すること。そうしないと、$optionsが使えません。$optionsだけだと、引数が渡されないので注意(symfonyの中身をみると、$argumentsと$optionsがマージをしているためなのが原因の様子)
ちなみに、$optionsの指定方法は色々できるみたいです。
<?php protected function execute($arguments = array(), $options = array()) { $this->runTask('sample:test', array('type'), array('type'=>1)); $this->runTask('sample:test', array('type'), array('--type'=>1)); $this->runTask('sample:test', array('type'), array('--type=1')); $this->runTask('sample:test', array('type'=>123), array('type'=>1)); $this->runTask('sample:test', array('type'=>123), array('--type'=>1)); $this->runTask('sample:test', array('type'=>123), array('--type=1')); }
アクションからタスクを呼び出す
ここは「symfony1.4 - action内であれこれ - | tech.kayac.com - KAYAC engineers' blog」を参考に。
$task = new sampleTestTask(sfContext::getInstance()->getEventDispatcher(), new sfFormatter()); $task->run(array('env', 'type'), array('env'=>'dev', 'type'=>1));
テストのタスク
<?php class sampleTestTask extends sfBaseTask { //protected function configure($arguments = array(), $options = array()) protected function configure() { $this->addArgument('env', sfCommandArgument::OPTIONAL, 'Environment', 'local'); $this->addArgument('type', sfCommandArgument::OPTIONAL, '', 'hogehoge'); $this->addOptions(array( new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'Environment', 'local'), new sfCommandOption('type', null, sfCommandOption::PARAMETER_OPTIONAL, ''), )); $this->namespace = 'sample'; $this->name = 'test'; } protected function execute($arguments = array(), $options = array()) { $this->log(var_dump($arguments)); $this->log(var_dump($options)); } }