我尝试创建"与框架无关"的业务类。这意味着,我的类不应该引用任何框架类,而应该只引用项目依赖项。
我尝试了以下代码,在 service.yml 中使用 typehint 但没有成功......
这是我的自定义界面:
namespace AppInterfaces;
interface EntityManagerInterface extends DoctrineORMEntityManagerInterface
{
}
这是我的框架不可知的业务
use AppInterfacesEntityManagerInterface;
class MyBusiness
{
public function __construct(EntityManagerInterface $em)
{
...
}
}
这是我的控制器,我在其中注入实体管理器:
use SymfonyBundleFrameworkBundleControllerAbstractController;
use DoctrineORMEntityManagerInterface;
class testController extends AbstractController
{
public function testAction(EntityManagerInterface $em)
{
$myBusiness = new MyBusiness($em);
}
}
所以我因为注入错误的类而收到 PHP 错误:
Argument 1 passed to AppBusinessMyBusiness::__construct() must implement interface AppInterfacesEntityManagerInterface, instance of DoctrineORMEntityManager given, called in /var/www/src/Controller/testController.php on line 7
如何将实体管理器正确注入我的框架无关业务?
谢谢
因为你通过了教义EntityManager
,这显然没有实现你的接口。
我真的不明白这样做的意义,因为并非所有框架的"实体管理器"都是相同的。
但是我能做的第一件事是制作某种"Adapter
",它将传递的EntityManager
封装在您自己的类中,该类实现您自己的EntityManagerInterface
,然后将其传递给您的业务。