Skip to content

Instantly share code, notes, and snippets.

@MadmanMonty
Forked from worenga/MyEventListener.php
Created June 28, 2012 09:39
Show Gist options
  • Save MadmanMonty/3010257 to your computer and use it in GitHub Desktop.
Save MadmanMonty/3010257 to your computer and use it in GitHub Desktop.
Doctrine2 Event Listener
services:
MyEventListener:
class: My\Bundle\Listener\MyEventListener
tags:
- { name: doctrine.event_listener, event: onFlush, method: onFlush }
<?php
namespace My\Bundle\Listener;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Events;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Mapping\ClassMetadata;
use My\Bundle\Entity\Event;
class MyEventListener {
private $em = null;
private $uow = null;
private $attachedEvents;
public function onFlush(OnFlushEventArgs $args) {
$this -> em = $args -> getEntityManager();
$eventManager = $this -> em -> getEventManager();
// Remove event, if we call $this->em->flush() now there is no infinite recursion loop!
$eventManager -> removeEventListener('onFlush', $this);
$this -> uow = $this -> em -> getUnitOfWork();
//Iterate through Insertions:
foreach ($this->uow->getScheduledEntityInsertions() as $entity) {
//Get the plain ClassName without Namespace
$className = join('', array_slice(explode('\\', get_class($entity)), -1));
$meta = $this -> em -> getClassMetadata(get_class($entity));
//... create your Entity...
$newEvent = new Event;
$newEvent->setName('...');
//...
$this -> em -> persist($newEvent);
$this -> em -> flush();
// recalculate changeset, since we might messed up the relations
$this -> em -> getUnitOfWork() -> recomputeSingleEntityChangeSet($meta, $entity);
}
//We can also iterate through planned deletions
foreach ($this->uow->getScheduledEntityDeletions() AS $entity) {
$className = join('', array_slice(explode('\\', get_class($entity)), -1));
//Search for old dependencies and delete them too...
$events = $this -> em -> getRepository('MyBundle:Event') -> findBy('myProperty'=>'value');
foreach ($events as $entity) {
$this -> em -> remove($entity);
}
}
}
$this -> em -> flush();
}
//Or even react on updates:
foreach ($this->uow->getScheduledEntityUpdates() as $key => $entity) {
$className = join('', array_slice(explode('\\', get_class($entity)), -1));
$meta = $this -> em -> getClassMetadata(get_class($className));
//ChangeSet is an array of key - array pairs.
//$changeSet['fieldname'] => array(0 => 'oldValue', 1 => 'newValue')
//if the target Value is i.e. a date, the indices 0 and 1 are i.e. DateTime Objects
$changeSet = $this -> uow -> getEntityChangeSet($entity);
//You can modify your Entities based on the Changes here..
//After Persisting:
$this->uow->computeChangeSet($meta, $entity)
}
}
//Re-attach since we're done
$eventManager -> addEventListener('onFlush', $this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment