如何从控制器运行 symfony 2 运行命令 [英] How can I run symfony 2 run command from controller
问题描述
我想知道如何从浏览器查询或控制器运行 Symfony 2 命令.
I'm wondering how can I run Symfony 2 command from browser query or from controller.
这是因为我无法在主机上运行它,并且每个 cron 作业都是由管理员设置的.
Its because I don't have any possibility on hosting to run it and every cron jobs are setted by admin.
我什至没有启用 exec()
功能,所以当我想测试它时,我必须将命令中的所有内容复制到某个测试控制器,这不是最佳解决方案.
I don't even have enabled exec()
function so when I want to test it, I must copy all content from command to some testing controller and this is not best solution.
推荐答案
参见官方文档 关于新版本 Symfony 的这个问题
See official documentation on this issue for newer versions of Symfony
您不需要从控制器执行命令的服务,我认为最好通过 run
方法而不是通过控制台字符串输入来调用命令,但是 官方文档建议你通过它的别名调用命令.另请参阅此答案.在 Symfony 2.1-2.6 上测试.
You don't need services for command execution from controller and, I think, it is better to call command via run
method and not via console string input, however official docs suggest you to call command via it's alias. Also, see this answer. Tested on Symfony 2.1-2.6.
您的命令类必须扩展 ContainerAwareCommand
// Your command
use SymfonyBundleFrameworkBundleCommandContainerAwareCommand;
class MyCommand extends ContainerAwareCommand {
// …
}
// Your controller
use SymfonyComponentConsoleInputArrayInput;
use SymfonyComponentConsoleOutputNullOutput;
class SomeController extends Controller {
// …
public function myAction()
{
$command = new MyCommand();
$command->setContainer($this->container);
$input = new ArrayInput(array('some-param' => 10, '--some-option' => true));
$output = new NullOutput();
$resultCode = $command->run($input, $output);
}
}
在大多数情况下,您不需要 BufferedOutput
(来自 Jbm 的 答案)并且检查 $resultCode 是否为 0
就足够了,否则出错.
In most cases you don't need BufferedOutput
(from Jbm's answer) and it is enough to check that $resultCode is 0
, otherwise there was an error.
这篇关于如何从控制器运行 symfony 2 运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!