I am using Doctrine 2 in a Zend Framework 2 application. Is there any way using ZF2 to inject dependencies into entities returned by Doctrine? Entities are constructed by Doctrine when retrieved from the database. So far as I know to inject dependencies in ZF2 I need to instantiate entities using Service Locator. I cannot see how I can integrate that with Doctrine without having to modify Doctrines code base. The only feasible solution I can see right now is to write a small service which takes the result returned from Doctrine and injects the required dependencies. Is there a more elegant solution?
Best Regards Christian
Look into the Doctrine EventManager, in particular, the postLoad lifecycle event, which is fired by the EventManager every time an entity is loaded from the database.
To hook it all into ZF2, you would need to do a couple of things.
First, write a Doctrine-Flavored event listener:
<?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'));
}
}
Then, in someplace like some Module.php (maybe there's a better place than onBootstrap, but whatever):
<?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 ) );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With