【发布时间】: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