首页 > 解决方案 > 使用“必须实现接口 Doctrine\ORM\EntityManagerInterface 错误”将 EntityManagerInterface 注入我的服务

问题描述

我在 ./src/Service 创建了一个服务,我想在我的服务中使用 Doctrine Entity Manager,所以我将它注入到__construct方法中:

命名空间应用\服务;

use App\Entity\Category;
use Doctrine\ORM\EntityManagerInterface;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;

class CommonPageGenerator
{
  /**
   * @var EntityManagerInterface
   */
  private $em;
  /**
   * @var Environment
   */
  private $templating;

  public function __construct(EntityManagerInterface $em, Environment $templating)
  {
    $this->em = $em;
    $this->templating = $templating;
  }

  public function page1($title){ return; }

}

然后我将此服务注入控制器中:

  /**
   * @Route("/overseas", name="overseas")
   * @param CommonPageGenerator $commonPageGenerator
   */
  public function overseas(CommonPageGenerator $commonPageGenerator)
  {
    return $commonPageGenerator->page1('overseas');
  }

但我收到以下错误:

传递给 App\Service\CommonPageGenerator::__construct() 的参数 1 必须实现接口 Doctrine\ORM\EntityManagerInterface,给定字符串,在 /Users/tangmonk/Documents/mygit/putixin.com/putixin_backend/var/cache/dev/ContainerB7I3rzx 中调用/getCommonPageGeneratorService.php 第 11 行

在此处输入图像描述

我的services.yaml文件:

parameters:

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
        bind:
          $em: 'doctrine.orm.default_entity_manager'

我正在使用 Symfony 4.3

标签: phpsymfonydependency-injectionsymfony4

解决方案


您不需要绑定$em到 Doctrine 实体管理器。

如果您删除该行并仅留下类型提示 ( __construct(EntityManagerInterface $em, Environment $templating) 就足够了。

因此离开你的__construct()方法是这样的:

// you can of course import the EngineInterface with a "use" statement. 
public function __construct(
                    EntityManagerInterface $em,
                    Environment $templating)
  {
    $this->em = $em;
    $this->templating = $templating;
  }

如果您这样做并删除绑定配置,则自动依赖注入应该自行工作。

(通常我会建议替换EnvironmentSymfony\Bundle\FrameworkBundle\Templating\EngineInterface, 以依赖框架提供的接口与模板组件集成。但是该组件及其集成已在 4.3 中被弃用,并将在 5.0 中删除;所以你可以直接依赖在树枝上。)

但是如果出于某种原因想要保留绑定,您应该在服务名称前加上一个@符号,这样 Symfony 就知道您正在尝试注入服务而不是字符串。像这样:

 bind:
          $em: '@doctrine.orm.default_entity_manager'

文档


推荐阅读