Custom Tasks in Symfony (1.0)

As users of symfony know, there are many useful command line tasks that are essential to developing your symfony projects (symfony cc, symfony propel-build-model, etc). Luckily symfony is set up so that you can easily create your own tasks to do specific things that you may need. The only problem that some people may have (such as me) is where the heck do you put these custom tasks.

After searching through the documentation and source code and doing some extensive experimentation, I’ve concluded that there are basically two places where you can place your custom tasks. The first option would be to actually put the task in the SF_SYMFONY_DATA_DIR/tasks directory. However, I don’t really like the approach of messing with the base symfony installation, so I looked into how I could put them inside a project.

After trying out different locations such as SF_PROJECT/data/tasks, SF_PROJECT/lib/data/tasks, I’ve concluded that there is only one way to put the custom task within your project. The solution is to create a plugin for the task. I suppose this actually makes sense so that you can easily re-use a task between projects.

Basically you will create the file for your custom task and place it in a plugin, such as the following:

SF_PROJECT_DIR/plugins/myTaskPlugin/data/tasks/sfPakeMyTask.php

Then you will create the actual task file. Here is a basic example to test it out:

  1.  
  2. <?php
  3.  
  4. pake_desc('test for a custom task');
  5. pake_task('my-test');
  6.  
  7. function run_my_test($task, $args)
  8. {
  9.  echo "\r\nRunning my-test!\r\n";
  10. }

Now you just need to go to the command line and type:

  1. $ symfony cc
  2. $ symfony tasks

You will see that your custom task is listed in the available tasks…awesome!

Now you can run the custom task just like any other and see the output from it.

  1.  
  2. $ symfony my-test
  3.  
  4. Running my-test!

So from there you can take a look at the tasks that are provided in symfony to get an idea of how to build your own. Symfony 1.1 will change all of this, and by the looks of things will be easier and more powerful to use. But this method should be useful for any of us that are still using symfony 1.0 for the present time.

Tags:

About marc

a Senior Software Engineer in Los Angeles, CA. He likes to receive comments :)