Last active
August 29, 2015 14:15
-
-
Save norbe/f2061598ecc112a7e531 to your computer and use it in GitHub Desktop.
PDO Transaction manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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