Run multiple Symfony console commands, from within a command

别来无恙 提交于 2019-12-10 18:51:45

问题


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?


回答1:


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).




回答2:


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


来源:https://stackoverflow.com/questions/41319602/run-multiple-symfony-console-commands-from-within-a-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!