Doctrine 1.2: Using postDelete to delete related files on filesystem -- with transaction support
Thi开发者_如何学Cs question is a sort of extension to this question:
Perform some cleanup when deleting a record in Symfony/Doctrine
I'm doing this and it's working fine, except for one problem: if the delete fails and the transaction is never committed, the postDelete method still runs and the files are deleted anyway.
What would be a good way to avoid this?
If you need to trigger something only when the transaction has actually been committed, you need to queue it in postDelete, and then perform it in a postTransactionCommit handler
$conn = Doctrine_Manager::connection(...);
$conn->addListener(new TransactionCommitListener());
class TransactionCommitListener extends Doctrine_EventListener {
public function postTransactionCommit(Doctrine_Event $event) {
if ($event->getInvoker()->getConnection()->getTransactionLevel() == 1) {
// do your filesystem deletes here
}
}
public function postTransactionRollback(Doctrine_Event $event) {
// clear your delete queue here
}
}
I've typically used a singleton to store the queue and fetched it statically. If you are using multiple connections, you'll want to have multiple queues.
The commit handler above only fires on the outermost commit, which is how Doctrine works with mysql, since it doesn't provide nested transactions. If your database provides nested transactions, and doctrine supports that, you might need to change that.
精彩评论