zend-framework2 - ZF2 with Doctrine 2 - 在实体中注入(inject)依赖项

标签 zend-framework2

我在 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/

相关文章:

php - ZF2 - 如何插入选择?

php - 分页时出错

doctrine-orm - 如何在学说2中创建数据库

php - ZF2 - ServiceManager 和 'aware' 接口(interface)

php - MySQL IN 关键字和 Zend Framework 2 更新查询

php - 如何使 Zf2 Apigilty 接受 header 中未设置接受的客户端请求

php - Zf2 float 验证无效但验证器消息为空

php - 从 ZF2 中通过 REST 请求发送的多部分数据获取文件内容

redirect - ZF2 在 Controller 外部使用重定向

php - Zend框架2 : How to write custom query using tablegateway