Symfony 2 is mainly used to create web application, however, sometimes you need to extend your app and need a command line tool to help perform tasks around the application. With symfony 1.4.x these were called tasks and it was possible to create a skeleton by using the symfony generate:task task.

Symfony 2 does not yet provide a tool for this yet, but creating a console command is actually quite simple:

  1. Under your Bundle, create a Command directory
  2. Inside Command create a new PHP class which will extend Symfony\Bundle\FrameworkBundle\Command\Command

This is the basic skeleton of ServerGroveBundle/Command/TestCommand.php to give an example

namespace Application\ServerGroveBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\Command;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class TestCommand extends Command

    protected function configure()

                ->addArgument('call', InputArgument::REQUIRED, 'Call')              
                ->addOption('user', 'u', InputOption::PARAMETER_OPTIONAL, 'Username', '')
                ->addOption('passwd', 'p', InputOption::PARAMETER_OPTIONAL, 'Password', '')


     * Executes the current command.
     * @param InputInterface  $input  An InputInterface instance
     * @param OutputInterface $output An OutputInterface instance
     * @return integer 0 if everything went fine, or an error code
     * @throws \LogicException When this abstract class is not implemented
    protected function execute(InputInterface $input, OutputInterface $output)
         // your code here.
         $arg1 = $input->getArgument('arg1');
         $options = $input->getOptions();

In the configure() method, you set the definition of the command, its arguments and options. Then you add the code to execute in the execute() method.

Now, when executing ./app/console help sg:test you will get:

 sg:test [-u|--user[="..."]] [-p|--passwd[="..."]] call 

 call       Call

 --user (-u) API  (default: )
 --passwd (-p) API  (default: )

If you need access to your database, you can get a reference to the document manager or entity manager with:

$dm = $this->container->get('doctrine.odm.mongodb.document_manager');

You can also look at commands in the included bundles in src/vendor/symfony/src/Symfony/Bundle to get more usage examples.