【问题标题】:Symfony autowire - What is the relationship between different service.yml files?Symfony autowire - 不同 service.yml 文件之间的关系是什么?
【发布时间】:2019-05-20 18:26:40
【问题描述】:

我正在将现有的Symfony 2.8 项目迁移到Symfony 3.4。在这个过程中,我想使用autowire 来自动配置/设置服务。

从 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 不会不起作用

类型错误:函数的参数太少 AppBundle\Controller\CustomExceptionController::__construct(), 0 传入 .../project/var/cache/dev/ContainerW0i3edc/getCustomExceptionControllerService.php 在第 11 行,预计正好 2 行

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

只有当我将autowire: true 添加到具体的服务定义中时,autowire 才会尝试设置服务。但是,我仍然收到以下消息:

无法自动装配服务 “AppBundle\Controller\CustomExceptionController”:参数“$debug” 方法“__construct()”没有类型提示,你应该配置它 明确的价值。

由于$debug 绑定在app/config/services.yml 中,所以这应该不是问题吗? 但是,它只有在我明确设置src/AppBundle/Resources/config/services.yml 中的参数时才有效。

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

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

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

【问题讨论】:

    标签: symfony autowired


    【解决方案1】:

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

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

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

    对于您的所有问题:

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

    如何解决您的问题?

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


    您可以在in documentation 或我的post with before/after examples 中阅读有关 Symfony 3.3+ DI 更改的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 2012-01-30
      • 2012-08-12
      • 2023-03-18
      • 1970-01-01
      • 2021-01-04
      相关资源
      最近更新 更多