我希望能够将服务注入(inject)到我的 Controller 中,所以我查看了 http://symfony.com/doc/current/cookbook/controller/service.html在对符号进行了一些摆弄之后(可能会更加一致,但无论如何),我的 WebTestCase 使用了服务定义条目。
但是 Controller 需要注入(inject)容器本身(并且确实通过默认框架 Controller 扩展了 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 表示法时,它直接从容器中返回 Controller ,而不是注入(inject)容器本身。
这是一个错误还是我错过了什么?
最佳答案
这不是错误。它按预期工作。此工作流程通常“保护”Controller as a Service
概念。这种方式你需要看Controller
作为常规 Service
.定期Service
你注入(inject)你需要的一切——如果你需要 Controller 本身——明确地注入(inject)它。
为了更清楚地解释它,我提到的这种“保护”有助于避免使用service:method
。符号在一处和 controller::method
或 bundle:controller:method
在另一个。
因此,如果不是这种“保护”,就很难说出具体的Controller
。是否被描述为服务,因为这取决于将在 Container
中首先调用哪种表示法积聚。
关于unit-testing - Symfony 2 Controller 即服务 : container not injected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18426819/