If you’re going to make multiple related updates to your database, you should use a transaction. Here’s how to do a transaction with Doctrine. This is essentially lifted from the official Doctrine documentation but it’s a little more to-the-point than theirs. Plus my version doesn’t fail silently.
<?php $conn = Doctrine_Manager::connection(); try { $conn->beginTransaction(); $myObject->save(); $myOtherObject->save(); $conn->commit(); } catch(Exception $e) { $conn->rollback(); throw new Exception($e->getMessage()); }
Nice, quick, easy and no fuss. Just what I was looking for.
I’ve written transactions in the past but forgotten where so this was extremely helpful.
Many Thanks.
Chris.
Thanks, Chris. Glad you found it helpful.
You seem to be throwing an Exception and *then* trying to rollback. That’s never going to work ;)
I think you’re right, Chippie. I changed my example. Thanks for pointing that out.
Isn’t preferable to put the beginTransaction outside the try/catch ?
Maybe. Why do you think it would be? To me it seems like it would probably be better to have absolutely everything inside of the try. That way, if any part fails, the whole thing fails.
Well, you’re right. I had in mind a case where the transaction don’t start, and then, a rollback will throw something like “No transaction started”.