How to Call Other Commands

How to Call Other Commands

If a command depends on another one being run before it you can call in the console command itself. This is useful if a command depends on another command or if you want to create a “meta” command that runs a bunch of other commands (for instance, all commands that need to be run when the project’s code has changed on the production servers: clearing the cache, generating Doctrine proxies, dumping web assets, …).

Use the [find()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Application.php "Symfony\Component\Console\Application::find()") method to find the command you want to run by passing the command name. Then, create a new Symfony\Component\Console\Input\ArrayInput with the arguments and options you want to pass to the command.

Eventually, calling the run() method actually runs the command and returns the returned code from the command (return value from command’s execute() method):

  1. // ...
  2. use Symfony\Component\Console\Command;
  3. use Symfony\Component\Console\Input\ArrayInput;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Output\OutputInterface;
  6. class CreateUserCommand extends Command
  7. {
  8. // ...
  9. protected function execute(InputInterface $input, OutputInterface $output): void
  10. {
  11. $command = $this->getApplication()->find('demo:greet');
  12. $arguments = [
  13. 'name' => 'Fabien',
  14. '--yell' => true,
  15. ];
  16. $greetInput = new ArrayInput($arguments);
  17. $returnCode = $command->run($greetInput, $output);
  18. // ...
  19. }
  20. }

Tip

If you want to suppress the output of the executed command, pass a Symfony\Component\Console\Output\NullOutput as the second argument to $command->run().

Caution

Note that all the commands will run in the same process and some of Symfony’s built-in commands may not work well this way. For instance, the cache:clear and cache:warmup commands change some class definitions, so running something after them is likely to break.

Note

Most of the times, calling a command from code that is not executed on the command line is not a good idea. The main reason is that the command’s output is optimized for the console and not to be passed to other commands.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.