Skip to content

Instantly share code, notes, and snippets.

@norbe
Last active August 29, 2015 14:15
Show Gist options
  • Save norbe/f2061598ecc112a7e531 to your computer and use it in GitHub Desktop.
Save norbe/f2061598ecc112a7e531 to your computer and use it in GitHub Desktop.
PDO Transaction manager
class Model {
...
private function startTransaction() {
$transactionManager = new TransactionManager($this->pdo);
$transactionManager->beginTransaction();
return $transactionManager;
}
public function save($data) {
try {
$transactionManager = $this->startTransaction();
...
$transactionManager->commit();
} catch(\Exception) {
$transactionManager->rollback();
}
}
}
<?php
/********************************************************************\
/* This file is part of the FREGIS System (http://www.fregis.cz) \
/* Copyright (c) 2012 Karel Hák, Martin Jelič, Jakub Kocourek \
/* /
/* @license Use it as you want /
/********************************************************************/
namespace Fregis\Database;
/**
* @author Karel Hák <[email protected]>
*/
class TransactionManager extends \Nette\Object {
/** @var \PDO */
private $pdo;
private $inTransaction;
public function __construct(\PDO $pdo) {
$this->pdo = $pdo;
}
public function beginTransaction() {
$this->inTransaction = $this->pdo->inTransaction();
if(!$this->inTransaction) {
return $this->pdo->beginTransaction();
}
}
function commit() {
if(is_null($this->inTransaction)) {
throw new \Nette\InvalidStateException('beginTransaction was not called before commit');
}
if(!$this->inTransaction && $this->pdo->inTransaction()) {
$this->pdo->commit();
}
$this->inTransaction = null;
}
function rollback() {
if(is_null($this->inTransaction)) {
throw new \Nette\InvalidStateException('beginTransaction was not called before commit');
}
if(!$this->inTransaction && $this->pdo->inTransaction()) {
$this->pdo->rollBack();
}
$this->inTransaction = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment