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