phpsymfony-componentssymfony-console

Run multiple Symfony console commands, from within a command


I have two commands defined in a Symfony console application, clean-redis-keys and clean-temp-files. I want to define a command clean that executes these two commands.

How should I do this?


Solution

  • See the documentation on How to Call Other Commands:

    Calling a command from another one is straightforward:

    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);
    
        // ...
    }
    

    First, you find() the command you want to execute by passing the command name. Then, you need to create a new ArrayInput with the arguments and options you want to pass to the command.

    Eventually, calling the run() method actually executes the command and returns the returned code from the command (return value from command's execute() method).