Magento 2:如何从另一个 CLI 命令 class 到 运行 CLI 命令?

Magento 2: How to run CLI command from another CLI command class?

我正在处理自定义 CLI 命令,我想知道从 PHP 代码(没有 shell_exec() 或类似代码)调用其他命令的最佳方法是什么。
例如:
当 运行 宁 "php bin/magento my:custom:command" 时,它会做它的事情,最终会 运行 "php bin/magento cache:flush"。

有任何想法吗?

谢谢

Magento CLI 建立在 Symfony 控制台之上。您可以使用此组件加载和 运行 其他命令:

$arguments = new ArrayInput(['command' => 'my:custom:command']);
$this->getApplication()->find('my:custom:command')->run($arguments, $output);

$arguments = new ArrayInput(['command' => 'cache:flush']);
$this->getApplication()->find('cache:flush')->run($arguments, $output);

更多信息here。虽然这对您来说不太可能成为问题,但请注意文档表明这并不总是最好的主意:

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.