Archive · This post is from a previous era of this site.
Changing the default Command on Symfony Console Component
A new feature that I purposed to Symfony Console Component and developed at SymfonyCon Hack Day was merged 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 ListCommand by default, with this feature you are now able to change that behavior by simply setting the Command you want to be the default. Let’s see how you can do it:
<?php
// src/Acme/Command/HelloWorldCommand.php
namespace Acme\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class HelloWorldCommand extends Command
{
protected function configure()
{
$this->setName('hello:world')
->setDescription('Outputs \'Hello World\'');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('Hello World');
}
}
Now that we have our HelloWorldCommand let’s create the application and make it the default command:
<?php
// application.php
use Acme\Command\HelloWorldCommand;
use Symfony\Component\Console\Application;
$command = new HelloWorldCommand();
$application = new Application();
$application->add($command);
$application->setDefaultCommand($command->getName());
$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 is available in the Symfony website.