php - 使用“必须实现接口 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
解决方案
您不需要绑定$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
, 以依赖框架提供的接口与模板组件集成。但是该组件及其集成已在 4.3 中被弃用,并将在 5.0 中删除;所以你可以直接依赖在树枝上。)
但是如果出于某种原因想要保留绑定,您应该在服务名称前加上一个@
符号,这样 Symfony 就知道您正在尝试注入服务而不是字符串。像这样:
bind:
$em: '@doctrine.orm.default_entity_manager'
文档。
推荐阅读
- javascript - 在两个 div 之间切换,打开后重置
- c - 在 C 中,如何将文本文件的不同行保存到不同的变量
- kubernetes - How can I view the config details of the current context in kubectl?
- ios - 内容不适合 UI 标签
- multithreading - 如何将写操作限制为 1k 记录/秒?
- php - 在 Woocommerce 单一产品中添加销售日期后的销售日期的自定义文本
- laravel - 任意数量的 whereHas 子句
- python-3.x - 同步客户端和服务器之间的数据传输
- python - 我怎样才能重写这个给我一个答案列表?
- java - 在 Android Studio 中模拟 AI 点击