【发布时间】:2016-12-25 08:04:25
【问题描述】:
我在 Symfony 控制台应用程序中定义了两个命令,clean-redis-keys 和 clean-temp-files。我想定义一个命令clean 来执行这两个命令。
我应该怎么做?
【问题讨论】:
标签: php symfony-components symfony-console
我在 Symfony 控制台应用程序中定义了两个命令,clean-redis-keys 和 clean-temp-files。我想定义一个命令clean 来执行这两个命令。
我应该怎么做?
【问题讨论】:
标签: php symfony-components symfony-console
请参阅How to Call Other Commands 上的文档:
从另一个调用命令很简单:
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); // ... }首先,您
find()通过传递命令名称来执行要执行的命令。然后,您需要创建一个新的ArrayInput,其中包含要传递给命令的参数和选项。最终,调用
run()方法实际上执行了命令并从命令返回返回的代码(从命令的execute()方法返回值)。
【讨论】:
$greetInput 或运行的去向或工作原理
获取应用实例,找到命令并执行:
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);
}
为避免代码重复,您可以创建通用方法来调用子命令。像这样的:
private function executeSubCommand(string $name, array $parameters, OutputInterface $output)
{
return $this->getApplication()
->find($name)
->run(new ArrayInput($parameters), $output);
}
【讨论】: