iLikeBreakfast
iLikeBreakfast

Reputation: 1565

Insert entity in preUpdate event

I'm trying to persist a History entity whenever a Message gets updated. I have too much going on behind the scenes to post all the code here and for it to make sense, but I've basically tracked the issue down to the UnitOfWork::commit method. There, the UOW first loops through the entityInsertions, and finding nothing, continues on to the entityUpdates. There the UOW's entityInsertions gets updated, but since it's already past that loop, it doesn't pick up that it still needs to persist some entities. Is there any way to force the UOW to "restart" this process? If so, how? I'm using Doctrine 2.4.

Thanks for any help!

Upvotes: 0

Views: 742

Answers (1)

iLikeBreakfast
iLikeBreakfast

Reputation: 1565

This might be the dirtiest solution ever, but what I ended up doing was basically the following...

  1. Create an onFlush event subscriber
  2. Inject the entire container into the subscriber (seeing as injecting only the entity manager will result in a circular reference error)
  3. Loop through the UnitOfWork's scheduledEntityUpdates and scheduledEntityInserts (I wasn't interested in deletes)
  4. Handle each scheduled update or insert which you are interested in (in my case, I marked each entity I was interested in with a LoggableInterface, just to know which entities are loggable)
  5. Handle the relevant object with a handler chain (This was just my own algorithm, yours may not require this. This was set up to handle logging of different LoggableInterface objects in different ways)
  6. Persist the entity (the actual history event) via the entity manager, and do the following:

    $classMeta = $this->entityManager->getClassMetadata(get_class($historyEntity));
    $this->entityManager->getUnitOfWork()->computeChangeSet($classMeta, $historyEntity);
    
  7. Profit

Hope this helps somebody!

Upvotes: 1

Related Questions