Skip to content

Instantly share code, notes, and snippets.

@taner-dll
Forked from datacow-com/transaction.php
Last active December 16, 2019 03:02
Show Gist options
  • Save taner-dll/7904058d7111ab1c5d37 to your computer and use it in GitHub Desktop.
Save taner-dll/7904058d7111ab1c5d37 to your computer and use it in GitHub Desktop.
Symfony 2 - Transaction
<?php
// Snippet for Symfony 2 application that uses Doctrine 2 to handle transactions
// It uses the names of the objects/doctrine repositories from the Beta 4 Manual of Symfony 2.
// Get the entity manager
$em = $this->getDoctrine()->getEntityManager();
// suspend auto-commit
$em->getConnection()->beginTransaction();
// Try and make the transaction
try {
// Get the account
$account = $this->getDoctrine()->getRepository('AcmeStoreBundle:Account')->find($id);
// Lower balance
$account->setBalance($account->getBalance() - 100);
// Save account
$em->persist($account);
$em->flush();
// Try and commit the transaction
$em->getConnection()->commit();
} catch (Exception $e) {
// Rollback the failed transaction attempt
$em->getConnection()->rollback();
throw $e;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment