Override symfony2 console commands?

Viewed 8143

Is it possible to override symfony2 app/console commands? For example, in the FOS UserBundle I'd like to add a few more fields it asks when it creates a user with its console create user command. Is this possible, or do I need to create my own console command in my own bundle?

4 Answers

Symfony 4 has removed bundle inheritance, but you can still override commands by decorating them. It's cleaner and doesn't require a bundle. Just add this to services.yaml:

services:
    App\Command\MyCustomCommand:
        decorates: command_you_want_to_override

Note that command_you_want_to_override is a service name. For older, pre-Symfony 3.3 commands it will be something in lowercase with dots and underscores (eg. doctrine_migrations.diff_command), for newer ones it will be a class name. You can find this name by inspecting its bundle's service config or by searching through output of debug:container. On Linux or macOS it would be:

php bin/console debug:container | grep Command

In Symfony (3.3) you can override console commands by following these links. https://symfony.com/doc/current/console/calling_commands.html and the options at https://symfony.com/doc/current/console/input.html

Code from symfony doc:

use Symfony\Component\Console\Input\ArrayInput;
// ...

protected function execute(InputInterface $input, OutputInterface $output)
{
    $command = $this->getApplication()->find('demo:greet');

    $arguments = array(
        'command' => 'demo:greet',
        'name'    => 'Fabien',
        '--yell'  => true,
    );

    $greetInput = new ArrayInput($arguments);
    $returnCode = $command->run($greetInput, $output);

    // ...
}
Related