Symfony autowire - 不同 service.yml 文件之间的关系是什么?

Symfony autowire - What is the relationship between different service.yml files?

我正在努力将现有的 Symfony 2.8 项目迁移到 Symfony 3.4。在这个过程中我想使用autowire来自动configure/setup服务。

来自 SF 2 我的项目仍然组织在不同的包中,因此我使用不同的 services.yml 文件。

似乎项目 services.yml 的设置没有(完全)应用到包特定的 services.yml 文件。 我想知道这是否符合预期,或者我的配置是否有问题。

具体问题:

// app/config/config.yml
imports:
    - { resource: "@AppBundle/Resources/config/services.yml" }
    ...


// app/config/services.yml
services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false
        bind:
            $debug: '%kernel.debug%'


// src/AppBundle/Resources/config/services.yml
services:
    AppBundle\Controller\CustomExceptionController:
        public: true
        #autowire: true
        #arguments:
        #    $debug: '%kernel.debug%'


// AppBundle\Controller\CustomExceptionController
class CustomExceptionController extends ExceptionController {
    public function __construct(\Twig_Environment $twig, $debug) {
        parent::__construct($twig, $debug);
        ....
    }
}

CustomExceptionController 仅在服务定义为 public 时有效。由于 _defaults 设置为创建 private 服务,因此需要手动定义。由于控制器属于 AppBundle 我想(现在)将此配置保留在捆绑包中 service.yml

但是,仅应用 public: true 无效:

Type error: Too few arguments to function AppBundle\Controller\CustomExceptionController::__construct(), 0 passed in .../project/var/cache/dev/ContainerW0i3edc/getCustomExceptionControllerService.php on line 11 and exactly 2 expected

虽然消息提到了缓存,但这不是缓存问题(删除文件夹并重新构建缓存不会改变任何内容)。

仅当我将 autowire: true 添加到具体服务定义时,自动装配才会尝试设置服务。但是,我仍然收到以下消息:

Cannot autowire service "AppBundle\Controller\CustomExceptionController": argument "$debug" of method "__construct()" has no type-hint, you should configure its value explicitly.

因为 $debug 绑定在 app/config/services.yml 这应该不是问题,对吗? 但是,它只有在我明确说明时才有效在 src/AppBundle/Resources/config/services.yml.

中设置参数

为什么 autowire: true 不适用于捆绑包 services.yml 中定义的服务?

为什么项目 services.yml 的绑定未应用于捆绑包 services.yml 中定义的服务?

这是预期的行为还是我的配置有问题?

Why is autowire: true not applied to the services defined in the bundle services.yml?

Why is the binding from the project services.yml not applied to the services defined in the bundle services.yml?

Is the expected behavior or is there something wrong with my config?

所有问题:

_defaults 仅应用于 本地定义的服务,而不是导入的服务。 那是因为这样的全局应用程序可能会破坏外部配置。

如何解决您的问题?

_defaults 部分添加到 src/AppBundle/Resources/config/services.yml 文件。


您可以阅读有关 Symfony 3.3+ DI 更改的更多信息in documentation or in my post with before/after examples