Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing Symfony 2控制器作为服务:未注入容器_Unit Testing_Symfony_Dependency Injection_Controller - Fatal编程技术网

Unit testing Symfony 2控制器作为服务:未注入容器

Unit testing Symfony 2控制器作为服务:未注入容器,unit-testing,symfony,dependency-injection,controller,Unit Testing,Symfony,Dependency Injection,Controller,我希望能够将服务注入到我的控制器中,所以我看了一下,在对符号做了一些修改之后(可能更一致,但无论如何),我有了使用服务定义条目的WebTestCase 但是控制器需要注入容器本身(并且确实通过默认的框架控制器扩展了ContainerWare),而FrameworkBundle中的ControllerResolver不这样做 查看代码(Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver::createController()),

我希望能够将服务注入到我的控制器中,所以我看了一下,在对符号做了一些修改之后(可能更一致,但无论如何),我有了使用服务定义条目的WebTestCase

但是控制器需要注入容器本身(并且确实通过默认的框架控制器扩展了ContainerWare),而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表示法时,它直接从容器返回控制器,而不是注入容器本身


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

这不是bug。它按预期工作。此工作流通常“保护”控制器即服务的概念。这样,您需要将
控制器
视为常规的
服务
。在常规
服务中
可以注入所需的所有内容—如果需要控制器本身—显式注入

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


因此,如果没有这种“保护”,就很难说明特定的
控制器是否被描述为服务,因为这将取决于在
容器
构建中首先调用哪个符号。

显然,这是“想要的”或至少是预期的行为:我应该注入一切或什么都不注入。我也可以这样做。这也是可行的:调用:[SETPACK,[ @ Service Engult容器] ]不能回答我自己的问题,但请考虑这个问题。这是故意的。它为您提供了一个根本不注入容器的选项。这是一个值得称赞的目标。只要基本控制器是ContainerWare,服务容器就应该一直注入它(如果控制器扩展它)。我同意你的看法,那是一种奇怪的行为。