使用“必须实现接口Doctrine \ ORM \ EntityManagerInterface错误”将EntityManagerInterface注入我的服务。

时间:2019-08-12 15:02:05

标签: php symfony dependency-injection symfony4

我已经在./src/Service中创建了一个服务,并且我想在我的服务中使用Doctrine Entity Manager,因此我将其注入到__construct方法中:

命名空间App \ Service;

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/中调用第11行上的dev / ContainerB7I3rzx / getCommonPageGeneratorService.php

enter image description here

我的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

1 个答案:

答案 0 :(得分:3)

您不需要将$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;
  }

如果执行此操作并删除绑定配置,则自动依赖项注入应自行工作。

(通常,我建议将Environment替换为Symfony\Bundle\FrameworkBundle\Templating\EngineInterface,以依赖框架提供的与模板组件集成的接口。但是this component and its integration have been deprecated in 4.3将会是被5.0删除;因此直接依赖Twig可以了。)

但是如果出于某种原因要让绑定保留在适当的位置,则应在服务名称前加上@符号,因此Symfony知道您正在尝试注入服务,并且不是字符串。像这样:

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

Docs