Skip to content

Instantly share code, notes, and snippets.

@intellix
Last active December 20, 2015 14:49
Show Gist options
  • Save intellix/6150124 to your computer and use it in GitHub Desktop.
Save intellix/6150124 to your computer and use it in GitHub Desktop.
Event Listeners in ZF2/Doctrine ORM
<?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;
}
}
<?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
}
<?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;
}
}
@kukoman
Copy link

kukoman commented Oct 23, 2014

super useful, thank you; but one question pops up, what is the most elegant way if i need to inject zf2 service manager into the village listener?
thx

@mikemix
Copy link

mikemix commented Jan 13, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment