首页 > 解决方案 > 不自动装配时捆绑控制器中的错误

问题描述

Symfony 文档指出公共包应该明确地配置它们的服务,而不是依赖于自动装配。因此,我使用以下内容在我的包中配置控制器服务。

<service id="blah\blah\SecurityController">
    <argument type="service" id="security.authentication_utils"/>
    <tag name="controller.service_arguments"/>
    <tag name="container.service_subscriber"/>
</service>

安全参数是因为我在登录方法中使用 authenticationUtils->getLastAuthenticationError()。

但是,这样的服务定义会产生弃用错误。User Deprecated: Auto-injection of the container for "blah\blah\SecurityController" is deprecated since Symfony 4.2. Configure it as a service instead. at /var/www/html/vendor/symfony/framework-bundle/Controller/ControllerResolver.php:64)

如果我只是简单地添加autowire="true"到上面的服务定义中,错误就会消失(此时我也不需要现有的参数)。但是,我想遵循 Symfony 关于显式配置的建议。

当我需要明确包含的 autowire 设置为 true 时,我错过了什么自动注入?

标签: symfony

解决方案


基于弃用,我假设您的控制器正在扩展 AbstractController。

有两种可能的方法来解决这种弃用:

  1. 如果您根本不使用 AbstractController 的功能或仅使用很少的功能,那么您根本不能扩展任何东西。例如,如果您只使用 AbstractController 中的一个函数,您可能会选择重新实现它以减少依赖关系。官方文档中也提到了这一点。

  2. 如果要继续扩展 AbstractController,则需要手动注入容器。比如像这样:

服务.xml

<service id="App\Controller\FooController">
    <call method="setContainer">
        <argument type="service" id="service_container"/>
    </call>
</service>

FooController.php

class FooController extends AbstractController {}

推荐阅读