问题描述
我想知道如何从浏览器查询或从控制器运行 Symfony 2 命令。
I'm wondering how can I run Symfony 2 command from browser query or from controller.
我甚至没有启用 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 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 Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
class MyCommand extends ContainerAwareCommand {
// …
}
// Your controller
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
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 run命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!