Skip to content

Instantly share code, notes, and snippets.

@ahmed-bhs
Forked from KaduNovoK/transaction.php
Created April 13, 2018 21:09
Show Gist options
  • Save ahmed-bhs/f92b0ec9458af6608aa45ace7843dc6e to your computer and use it in GitHub Desktop.
Save ahmed-bhs/f92b0ec9458af6608aa45ace7843dc6e to your computer and use it in GitHub Desktop.
Transactions in Symfony 2 and Doctrine 2
<?php
// Code sample to use Transactions
// Get the Entity Manager
$em = $this->getDoctrine()->getEntityManager();
// Suspend the auto-commit
$em->getConnection()->beginTransaction();
try {
// Get the entity
$entity = $this->getDoctrine()->getRepository('YourBundle:EntityName')->find($id);
// Code changing the entity properties...
// Save the Entity
$em->persist($entity);
$em->flush();
// Commit the transaction
$em->getConnection()->commit();
} catch (Exception $e) {
// Rollback on error
$em->getConnection()->rollback();
throw $e;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment