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 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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?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 should be is available in the Symfony website soon.

comments powered by Disqus