首页 > 解决方案 > Symfony:在服务中显式定义容器

问题描述

更新后我有这个弃用:

Since symfony/dependency-injection 5.1: The "Symfony\Component\DependencyInjection\ContainerInterface" autowiring alias is deprecated. Define it explicitly in your app if you want to keep using it. It is being referenced by the "App\Service\ImportService" service.

这是我的ImportService

<?php

namespace App\Service;

use Symfony\Component\DependencyInjection\ContainerInterface;

class ImportService
{
    private $doctrine;
    private $em;

    public function __construct(ContainerInterface $container)
    {
        $this->doctrine = $container->get('doctrine'); //needed for database queries
        $this->em = $this->doctrine->getManager(); //needed for database queries
    }

    /** more methods here **/

}

那么我该如何明确表达呢?我用谷歌搜索了一下,我认为我必须以services.yml某种方式将它添加到我的文件中。但我不确定我必须如何为每个服务课程做这件事?

标签: symfonydependency-injection

解决方案


我刚刚创建了一个新的 5.1 应用程序并没有得到折旧。Symfony 确实不鼓励注入全局容器。所以我对它被贬值并不感到惊讶。

要修复该消息,您需要做的就是显式定义 ContainerInterface 别名:

# services.yml or yaml 
services:
    Symfony\Component\DependencyInjection\ContainerInterface: '@service_container'

这应该够了吧。但是,由于您似乎正在迁移到 5.1,那么您应该开始重构您的代码,并且只注入特定类需要的内容。这不是强制性的,但可以帮助您避免出现问题:

class ImportService
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em
    }

推荐阅读