我尝试创建“框架不可知”的业务类。这意味着,我的类不应该有任何对任何框架类的引用,只有项目依赖项。
我尝试了以下代码,在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注入到我的框架不可知业务中?
谢谢
发布于 2019-05-07 22:07:25
因为你通过了Doctrine的EntityManager,它显然没有实现你的接口。
我真的不明白这样做的意义,因为并不是所有框架的"EntityManager“都是一样的。
但我能做的第一件事就是做一些"Adapter“,它将把传递的EntityManager封装在你自己的类中,实现你自己的EntityManagerInterface,然后把它传递给你的业务。
https://stackoverflow.com/questions/56008009
复制相似问题