当实体保存在我的应用程序中时,我想将其slug
字段添加到查找表中。为了尽可能减少干扰,我编写了一个事件订阅者。根据这篇文章,我不能INSERT
参加postUpdate
活动,所以我尝试了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;
}
}
但是,当我现在尝试保存实体时registerSlugs
,无论是在更新还是新插入时,都不会调用该方法。
我哪里做错了?