我在 Zend Framework 2 应用程序中使用 Doctrine 2。有没有办法使用 ZF2 将依赖项注入(inject)到 Doctrine 返回的实体中?当从数据库中检索实体时,实体由 Doctrine 构建。据我所知,要在 ZF2 中注入(inject)依赖项,我需要使用 Service Locator 实例化实体。我看不出如何在无需修改 Doctrine 代码库的情况下将其与 Doctrine 集成。我现在能看到的唯一可行的解决方案是编写一个小服务,它获取从 Doctrine 返回的结果并注入(inject)所需的依赖项。有没有更优雅的解决方案?
最好的祝福
基督教
最佳答案
看教义EventManager ,特别是 postLoad生命周期事件,每次从数据库加载实体时由 EventManager 触发。
要将其全部连接到 ZF2,您需要做几件事。
首先,编写一个 Doctrine-Flavored 事件监听器:
<?php
class InjectStuffListener {
private $sl;
public function __construct($serviceLocator){
$this->sl = $serviceLocator;
}
public function postLoad($eventArgs){
$entity = $eventArgs->getEntity;
$entity->setThingToBeInjected($this->sl->get('some.thing'));
}
}
然后,在某个 Module.php 之类的地方(也许有比 onBootstrap 更好的地方,但无论如何):
<?php
public function onBootstrap(){
$sm = $e->getApplication()->getServiceManager();
$em = $sm->get('doctrine.entitymanager.orm_default');
$dem = $em->getEventManager();
$dem->addEventListener(array( \Doctrine\ORM\Events::postLoad ), new InjectStuffListener( $sm ) );
}
关于zend-framework2 - ZF2 with Doctrine 2 - 在实体中注入(inject)依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13334136/