Changing the default Command on Symfony Console Component

1 minute read

A new feature that I purposed to Symfony Console Component and developed at SymfonyCon Hack Day was merged this week and will be available since version 2.5+.

The feature will allow you to change the default Command when you are creating Console Applications.

Usage

Before this if you don’t provide the command you want to execute it executes the ListCommandby default, with this feature you are now able to change that behavior by simple setting the Command you want to be the default. Let’s see how you can do it:

 1 // src/Acme/Command/HelloWorldCommand.php
 2 namespace Acme\Command;
 3 use Symfony\Component\Console\Command\Command;
 4 use Symfony\Component\Console\Input\InputInterface;
 5 use Symfony\Component\Console\Output\OutputInterface;
 6 class HelloWorldCommand extends Command
 7 {
 8     protected function configure()
 9     {
10         $this->setName('hello:world')
11             ->setDescription('Outputs \'Hello World\'');
12     }
13     protected function execute(InputInterface $input, OutputInterface $output)
14     {
15         $output->writeln('Hello World');
16     }
17 }

Now that we have our HelloWorldCommand let’s create the application and make it the default command:

1 // application.php
2 use Acme\Command\HelloWorldCommand;
3 use Symfony\Component\Console\Application;
4 $command = new HelloWorldCommand();
5 $application = new Application();
6 $application->add($command);
7 $application->setDefaultCommand($command->getName());
8 $application->run();

Let’s execute it:

$ php application.php
$ Hello World

Simple, if you want to list all commands you just need to do php app.php list.

Limitation

The default command does not accept arguments only options.

Note: I added a new entry to Symfony Console Component documentation that should be is available in the Symfony website soon.

Leave a Comment