gpt4 book ai didi

php - 使用 `must implement interface Doctrine\ORM\EntityManagerInterface error` 将 EntityManagerInterface 注入(inject)我的服务

转载 作者:行者123 更新时间:2023-12-03 23:10:58 25 4
gpt4 key购买 nike

我在 ./src/Service 创建了一个服务,我想在我的服务中使用 Doctrine Entity Manager,所以我将它注入(inject)到 __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; }

}

然后我将此服务注入(inject) Controller 中:
  /**
* @Route("/overseas", name="overseas")
* @param CommonPageGenerator $commonPageGenerator
*/
public function overseas(CommonPageGenerator $commonPageGenerator)
{
return $commonPageGenerator->page1('overseas');
}

但我收到以下错误:

Argument 1 passed to App\Service\CommonPageGenerator::__construct() must implement interface Doctrine\ORM\EntityManagerInterface, string given, called in /Users/tangmonk/Documents/mygit/putixin.com/putixin_backend/var/cache/dev/ContainerB7I3rzx/getCommonPageGeneratorService.php on line 11



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

最佳答案

您不需要绑定(bind)$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;
}

如果你这样做, 删除 绑定(bind)配置,自动依赖注入(inject)应该自己工作。

(通常我会建议将 Environment 替换为 Symfony\Bundle\FrameworkBundle\Templating\EngineInterface ,以依赖于框架提供的接口(interface)以与模板组件集成。但是 this component and its integration have been deprecated in 4.3 ,并且将在 5.0 中删除;所以你可以直接依赖于枝条。)

但如果出于某种原因想要保留绑定(bind),则应在服务名称前加上 @符号,因此 Symfony 知道您正在尝试注入(inject)服务而不是字符串。像这样:
 bind:
$em: '@doctrine.orm.default_entity_manager'

Docs .

关于php - 使用 `must implement interface Doctrine\ORM\EntityManagerInterface error` 将 EntityManagerInterface 注入(inject)我的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57463692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com