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?
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?
Get the application instance, find the commands and execute them:
protected function configure()
{
$this->setName('clean');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$app = $this->getApplication();
$cleanRedisKeysCmd = $app->find('clean-redis-keys');
$cleanRedisKeysInput = new ArrayInput([]);
$cleanTempFilesCmd = $app->find('clean-temp-files');
$cleanTempFilesInput = new ArrayInput([]);
// Note if "subcommand" returns an exit code, run() method will return it.
$cleanRedisKeysCmd->run($cleanRedisKeysInput, $output);
$cleanTempFilesCmd->run($cleanTempFilesInput, $output);
}
To avoid code duplication, you can create generic method to call a subcommand. Something like this:
private function executeSubCommand(string $name, array $parameters, OutputInterface $output)
{
return $this->getApplication()
->find($name)
->run(new ArrayInput($parameters), $output);
}
See the documentation on How to Call Other Commands: