symfony1.2でバッチ処理を作るにはどうすればいいの?
symfony1.2 では generate:task コマンドが用意されているのでそれを利用します。
- まず、ジェネレートコマンドでひな形を作る
ジェネレートコマンドを実行すると、
[code] % ./symfony generate:task foo:sample [/code]
fooSampleTask.class.php というファイルが作成される
[php] // lib/task/fooSampleTask.class.php addArguments(array( // new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'), // ));
$this->addOptions(array(
new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name'),
new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'propel'),
// add your own options here
));
$this->namespace = 'foo';
$this->name = 'sample';
$this->briefDescription = '';
$this->detailedDescription = <<configuration);
$connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
// add your code here
} } [/php]
<li><strong>execute 関数をカスタマイズする</strong></li>
『add your code here』の下に実際の処理を記述していきます。
[php] protected function execute($arguments = array(), $options = array()) { // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
// DB アクセスも普通に使える
$obj = BookPeer::retrieveByPK(3);
var_dump($obj);
// ログも便利
$this->log('処理終了');
} [/php]
<li><strong>バッチ処理を実行する</strong></li>
[code] % ./symfony foo:sample [/code]
<li><strong>引数を使いたいとき</strong></li>
[php] protected function configure() { // // add your own arguments here $this->addArguments(array( new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'), )); [/php]
configure 関数の先頭のコメントを外すと my_arg 引数が有効になり、execute 関数の引数 $arguments['my_arg'] で利用できるようになります。
[php] % ./symfony foo:sample aaa // print_r($arguments); Array ( [task] => foo:sample [my_arg] => aaa ) [/php]
<li>他にも</li>
symfony/task/project とか symfony/task/generator とか
symfony のライブラリー内のタスクにサンプルになりそうなファイルがあるので参考にしてください。