Reputation: 414
I'm using doctrine-mongodb-odm-1.0.0-BETA10
and trying to provide some custom logic based on \InitialDocument
while preUpdate
event running.
Lets say \InitialDocument
obtained some state which must behave as initial one for new \StateDocument
. I'm doing something like this:
class InitDocListener implements \Doctrine\Common\EventSubscriber {
public function getSubscribedEvents()
{
return [
Events::preUpdate
];
}
public function preUpdate($args){
$document = $args->getDocument();
if($document instanceOf InitialDocument && $document->getState() == 'mine'){
$stateDocument = new \StateDocument();
$stateDocument->setInitDocument($document);
$args->getDocumentManager()->persist($stateDocument);
//no flush cause recursion happens
}
}
}
prePersist
event by \StateDocument
happens, but it will not persist new document in db. and postPersist
event accordingly will never be fired.
There is some more custom logic but all in event scope. At some point that logic may throw an Exception which must stop update event of InitialDocument
so InitialDocument
state depends of \StateDocument
creation process at business scope.
How can I solve this problem? preFlush
event to run before changeSet recalculation do not determine InitialDocument
instance. So it is some kind of trick to "search" updates at preFlush
and cause me to think it is not proper way. Please advise me in proper one. Thanks.
Upvotes: 2
Views: 1703
Reputation: 6922
I created a test case for your use case here. One thing that stood out from the code in your question was that you weren't calling recomputeSingleDocumentChangeSet()
on the document you were modifying during the lifecycle callback, as is mentioned in the preUpdate
documentation. But even with that call, the new document will not be inserted. This is due to the fact that UnitOfWork executes updates after insertions and upserts. The full order can be seen in UnitOfWork's commit()
method:
When the preUpdate
event is dispatched, upserts/inserts for new documents have already happened. Even with a call to recomputeSingleDocumentChangeSet()
, you end up scheduling the document for insertion but UnitOfWork ignores this and ultimately unsets it when clearing out all of the schedule queues here.
While a simple solution would be for ODM to check for additional inserts after processing updates, that could lead to an infinite loop in some situations. The UnitOfWork ordering predates my work on the project, but I the risk of looping might have been a concern when the original implementation was conceived.
As a work-around, you may want to have the listener dump the new documents to be inserted into some other container (or the listener itself) and then check after the fact for additional documents to be persisted/flushed.
Upvotes: 5