查看 Doctrine 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 ) );
}