【问题标题】:Symfony4 Inject EntityManagerInterface into framework agnostic classSymfony4 将 EntityManagerInterface 注入到与框架无关的类中
【发布时间】:2019-05-06 15:15:26
【问题描述】:

我尝试创建“与框架无关”的业务类。这意味着,我的类不应该引用任何框架类,只有项目依赖项。

我尝试了以下代码,在 service.yml 中使用 typehint 没有成功...

这是我的自定义界面:

namespace App\Interfaces;

interface EntityManagerInterface extends \Doctrine\ORM\EntityManagerInterface
{
}

这是我的框架无关业务

use App\Interfaces\EntityManagerInterface;

class MyBusiness
{
    public function __construct(EntityManagerInterface $em)
    {
        ...
    }
}

这是我注入 EntityManager 的控制器:

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Doctrine\ORM\EntityManagerInterface;

class testController extends AbstractController
{
    public function testAction(EntityManagerInterface $em)
    {
        $myBusiness = new MyBusiness($em);
    }
}

所以我得到了注入错误类的 PHP 错误:

Argument 1 passed to App\Business\MyBusiness::__construct() must implement interface App\Interfaces\EntityManagerInterface, instance of Doctrine\ORM\EntityManager given, called in /var/www/src/Controller/testController.php on line 7

如何将 EntityManager 正确地注入到我的框架无关业务中?

谢谢

【问题讨论】:

    标签: php interface symfony4 php-7 entitymanager


    【解决方案1】:

    因为您传递了 Doctrine 的 EntityManager 显然没有实现您的接口。

    我不太明白这样做的意义,因为并非所有 Framework 的“EntityManager”都是相同的。

    但我能做的第一件事是制作某种“Adapter”,它将传递的EntityManager 封装在您自己的类中,该类实现您自己的EntityManagerInterface,然后将其传递给您的业务。

    【讨论】:

      猜你喜欢
      • 2020-07-27
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      相关资源
      最近更新 更多