3

我希望能够将服务注入到我的控制器中,所以我查看了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 表示法时,它直接从容器中返回控制器,而不是注入容器本身。

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

4

1 回答 1

0

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

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

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

于 2015-08-11T11:36:59.910 回答