Casey
Casey

Reputation: 1981

MySql PDO beginning a transaction and passing it to objects

Will this work? I'd test it but I don't know how to crash things half way though.

$db = DB::getDB();
try{
    $db->begintransaction();
    Invoice::saveInvoice($info, $db);
    InvoiceDetails::saveDetails($moreInfo, $db);
    $db->commit();
}catch(Exception $e){
    $db->rollback();
}

And if it does work is there anything that could bite me in the butt besides doing something that causes a implicit commit?

Upvotes: 0

Views: 38

Answers (1)

Phil
Phil

Reputation: 164766

The only thing I'd do is fix up your exception handling. For example

catch (Exception $e) {
    $db->rollback();
    throw $e;
}

Doing this lets you safely rollback the transaction as well as letting the error bubble up further in your application.

You could even wrap the inner exception (which will probably be a PDOException) with one of your choosing, eg

$db->rollback();
throw new RuntimeException('Error saving invoice details', 0, $e);

To "crash things half way though", simply throw an exception within one of your save* methods, eg

throw new Exception('KA-BLAM!');

Upvotes: 2

Related Questions