Last active
December 20, 2015 14:49
-
-
Save intellix/6150124 to your computer and use it in GitHub Desktop.
Event Listeners in ZF2/Doctrine ORM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Application\Controller; | |
use Zend\Mvc\Controller\AbstractActionController; | |
class VillageController extends AbstractActionController | |
{ | |
private $em; | |
public function indexAction() | |
{ | |
$this->identity()->getVillage()->setName('blah'); | |
$this->getEntityManager()->flush(); | |
} | |
public function getEntityManager() | |
{ | |
if (!$this->em) { | |
$this->em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); | |
} | |
return $this->em; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Application\Entity; | |
use Doctrine\ORM\Mapping as ORM; | |
/** | |
* Village | |
* | |
* @ORM\Table(name="villages") | |
* @ORM\Entity | |
* @ORM\EntityListeners({"Application\Listener\Village"}) | |
*/ | |
class Village | |
{ | |
// etc etc | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Application\Listener; | |
use Doctrine\ORM\Event\PreUpdateEventArgs; | |
use Application\Entity; | |
class Village | |
{ | |
public function preUpdate(Entity\Village $village, PreUpdateEventArgs $event) | |
{ | |
var_dump($village);exit; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
check out this, it's SF2 altough problem is similiar:
http://egeloen.fr/2013/12/01/symfony2-doctrine2-entity-listener-as-serice/
I would create own entity listener resolver, extend the DefaultEntityListenerResolver. It would be better not to inject the service locator. It's a bad habit as ocramius said. It would be better then to inject the SM to the resolver, check if the listener is available through SM and create it that way.