Friday 25 January 2013

Create task using symfony and run it form action

Create MyTask.class.php in /lib/Task folder. It should look like this:
/**
 * MyTask class.
 *
 * @author ...
 */
class MyTask extends sfPropelBaseTask
{

  /**
   * Execute configure method.
   * 
   */
  protected function configure()
  {
    $this->addOptions(array(
      new sfCommandOption('application', NULL, sfCommandOption::PARAMETER_OPTIONAL, 'The application name', 'front'),
      new sfCommandOption('env', NULL, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', NULL, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'propel'),
    ));

    $this->namespace = 'namespace';
    $this->name = 'myTask';
    $this->briefDescription = 'Do Task';
    $this->detailedDescription = 'Do Task desc';
  }

  /**
   * Execute execute method.
   * 
   * @param array $arguments
   * @param array $options
   * 
   */
  protected function execute($arguments = array(), $options = array())
  {
    sfContext::createInstance($this->configuration);
    
    //Do Task

  }

}
And now, run it from action that you need:
    $dispatcher = sfContext::getInstance()->getEventDispatcher();
    $formatter = new sfFormatter();
    $task = new ReminderToWriteReviewTask($dispatcher, $formatter);
    chdir(sfConfig::get('sf_root_dir'));
    $task->run(array(), array('connection' =>  sfConfig::get('connection')));
You can also call the task, as it should be called, from command line
    php symfony namespace:myTask