When an entity is saved in my app, I want to add its slug
field to a lookup table. To make this as least intrusive as possible, I wrote up an event subscriber. According to this post, I cannot INSERT
on postUpdate
events, so I tried postFlush
:
class SlugsSubscriber implements EventSubscriber {
public function getSubscribedEvents() {
return array('postFlush');
}
public function postFlush(PostFlushEventArgs $args) {
$em = $args->getEntityManager();
$needsFlush = false;
error_log("postFlush");
foreach ($em->getUnitOfWork()->getScheduledEntityInsertions() as $entity) {
// To prevent short-circuit
$tmp = $this->registerSlugs($entity, $entityManager);
if($tmp) $needsFlush = true;
}
foreach ($em->getUnitOfWork()->getScheduledEntityUpdates() as $entity) {
// To prevent short-circuit
$tmp = $this->registerSlugs($entity, $entityManager);
if($tmp) $needsFlush = true;
}
if($needsFlush) {
error_log("Flushing");
$em->flush();
}
}
protected function registerSlugs($entity, EntityManager $entityManager) {
error_log("register slugs");
if($entity instanceof Product) {
$this->registerProductSlugs($entity, $entityManager);
return true;
} elseif($entity instanceof Category) {
$this->registerCategorySlugs($entity, $entityManager);
return true;
}
return false;
}
}
However, when I try to save an entity now, the method registerSlugs
is never called, neither on an update nor a new insertions.
Where did I go wrong?