Transactions with Doctrine

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());
}

7 Responses to “Transactions with Doctrine”

  1. 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.

  2. jason says:

    Thanks, Chris. Glad you found it helpful.

  3. Chippie says:

    You seem to be throwing an Exception and *then* trying to rollback. That’s never going to work ;)

  4. jason says:

    I think you’re right, Chippie. I changed my example. Thanks for pointing that out.

  5. Rénald Casagraude says:

    Isn’t preferable to put the beginTransaction outside the try/catch ?

  6. jason says:

    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.

  7. Rénald Casagraude says:

    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”.