Home > Tags > bat

bat

symfony1.2でバッチ処理を作るにはどうすればいいの?

symfony1.2 では generate:task コマンドが用意されているのでそれを利用します。

  1. まず、ジェネレートコマンドでひな形を作る
  2. ジェネレートコマンドを実行すると、

    % ./symfony generate:task foo:sample

    fooSampleTask.class.php というファイルが作成される

    // lib/task/fooSampleTask.class.php
    <?php

    class fooSampleTask extends sfBaseTask
    {
      protected function configure()
      {
        // // add your own arguments here
        // $this->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 = <<<EOF
    The [foo:sample|INFO] task does things.
    Call it with:

      [php symfony foo:sample|INFO]
    EOF;
      }

      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();

        // add your code here
      }
    }

  3. execute 関数をカスタマイズする
  4. 『add your code here』の下に実際の処理を記述していきます。

    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('処理終了');
      }

  5. バッチ処理を実行する
  6. % ./symfony foo:sample

  7. 引数を使いたいとき
  8. protected function configure()
      {
        // // add your own arguments here
        $this->addArguments(array(
          new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
        ));

    configure 関数の先頭のコメントを外すと my_arg 引数が有効になり、execute 関数の引数 $arguments['my_arg'] で利用できるようになります。

    % ./symfony foo:sample aaa
    // print_r($arguments);
    Array
    (
        [task] => foo:sample
        [my_arg] => aaa
    )

  9. 他にも
  10. symfony/task/project とか
    symfony/task/generator とか

    symfony のライブラリー内のタスクにサンプルになりそうなファイルがあるので参考にしてください。

    参考
    第16章 - アプリケーションの運用ツール

ホーム > タグ > bat

ぴくちゃー
ブログパーツ

ページの上部に戻る