I know this is not entirely revolutionary, but I saw a whole plugin dedicated to it, which I found to be quite overkill (when a simple blog post will most likely do!).

For symfony 1.3, it should go something like this:

    chdir(sfConfig::get('sf_root_dir')); // Trick plugin into thinking you are in a project directory
    $task = new sfMyVerySpecialTask(sfContext::getInstance()->getEventDispatcher(), new sfFormatter());
    $task->run(array('argument_name' => 'argument'), array('option_name' => 'option'));

Seems to work for me. Will report back if anything seems wonky.

** UPDATE **
It has been mentioned that calling sfContext is to be avoided at all costs. I would advise wrapping the task in a if(sfContext::hasInstance()) statement, to be sure a context exists.

5 comments

  • Olivier - February 23, 2010

    expect that with sfContext::getInstance() you kill kittens. Please use $this->getContext() within an action (and do not call a task from the model !)

  • valter779 - April 14, 2010

    is there a way to run task from unit/functional test ?

  • admin - April 29, 2010

    In your test bootstraps (unit or functional), you should be retrieving an instance of ProjectConfiguration:

    // Functional Tests
    $configuration = ProjectConfiguration::getApplicationConfiguration($app, ‘test’, isset($debug) ? $debug : true);

    //Unit Tests:
    $configuration = ProjectConfiguration::hasActive() ? ProjectConfiguration::getActive() : new ProjectConfiguration(realpath($_test_dir . ‘/..’));

    You can then use this to create and run your task:

    $task = new sfFooTask($configuration->getEventDispatcher(), new sfFormatter());
    $task->run($argumentsArray, $optionsArray));

    I hope this helps!

  • Dennis Gearon - July 13, 2010

    Great! Thanks for the help. I’ll be able to use my super duper task now, from a test harness. Oh boy, (deep sigh), getting closer to understanding the Symfony framework and now they’re going to change it!!! Oh well, it’ll have some similar features.

  • Dennis Gearon - July 16, 2010

    found out one thing that this approach WON’T do . . drop and recreate the database repetatively for testing with PHPUnit. Apparently, those actions are not transactionalble, or act like it with Postgres/Symfony/Apache/PHPUnit. See my blog post to learn ‘easier that I had to’ how to get around that issue.

    http://php-rest-i18n.blogspot.com/2010/07/testing-symfony-apps-with-phpunit.html
    I DID use the method above for reloading the fixture files, and it worked great.

Add comment