【问题标题】:Symfony 2 Controller as a Service: container not injectedSymfony 2 控制器即服务:容器未注入
【发布时间】:2013-08-25 07:48:28
【问题描述】:

我希望能够将服务注入到我的控制器中,所以我查看了http://symfony.com/doc/current/cookbook/controller/service.html,并在对符号进行了一些摆弄之后(可能更一致,但无论如何)我有我的 WebTestCase 使用服务定义条目.

但控制器需要注入容器本身(并且确实通过默认框架控制器扩展了 ContainerAware),而 FrameworkBundle 中的 ControllerResolver 并没有这样做。

看代码(Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver::createController())这并不奇怪:

protected function createController($controller)
{
    if (false === strpos($controller, '::')) {
        $count = substr_count($controller, ':');
        if (2 == $count) {
            // controller in the a:b:c notation then
            $controller = $this->parser->parse($controller);
        } elseif (1 == $count) {
            // controller in the service:method notation
            list($service, $method) = explode(':', $controller, 2);

            return array($this->container->get($service), $method);
        } else {
            throw new \LogicException(sprintf('Unable to parse the controller name "%s".', $controller));
        }
    }

    list($class, $method) = explode('::', $controller, 2);

    if (!class_exists($class)) {
        throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
    }

    $controller = new $class();
    if ($controller instanceof ContainerAwareInterface) {
        $controller->setContainer($this->container);
    }

    return array($controller, $method);
}

显然在使用 service:method 表示法时,它直接从容器中返回控制器,而不是注入容器本身。

这是一个错误还是我遗漏了什么?

【问题讨论】:

  • 显然这是“想要的”或至少是预期的行为:我应该注入任何东西或什么都不注入。我可以忍受。
  • 这也有效:调用:- [setContainer, ["@service_container"]]
  • 无法回答我自己的问题,但认为这个问题已解决。
  • 是的。这是有意的。它为您提供了完全不注入容器的选项。这是一个值得称赞的目标。
  • 一旦基本控制器是 ContainerAware,服务容器应该一直注入它(如果控制器扩展它)。我同意你的看法,这是一种奇怪的行为。

标签: unit-testing symfony dependency-injection controller


【解决方案1】:

这不是错误。它按预期工作。此工作流程通常“保护”Controller as a Service 概念。这样,您需要将Controller 视为常规Service。在常规的Service 中,你注入你需要的一切——如果你需要控制器本身——显式注入它。

为了更清楚地解释它,我提到的这种“保护”有助于避免在一个地方使用service:method 符号,而在另一个地方使用controller::methodbundle:controller:method

因此,如果不是这种“保护”,则很难说明特定的 Controller 是否被描述为服务,因为这取决于在 Container 构建中首先调用哪个符号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多