如何从控制器运行 symfony 2 run 命令 [英] How can I run symfony 2 run command from controller

查看:18
本文介绍了如何从控制器运行 symfony 2 run 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何从浏览器查询或控制器运行 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 run 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆