Skip to content

Instantly share code, notes, and snippets.

@SGudbrandsson
Last active February 11, 2016 13:11
Show Gist options
  • Save SGudbrandsson/541a8c12d7ec30f6d2f2 to your computer and use it in GitHub Desktop.
Save SGudbrandsson/541a8c12d7ec30f6d2f2 to your computer and use it in GitHub Desktop.
Kohana 3.3 ORM extension for safe database transactions
<?php defined('SYSPATH') OR die('No direct script access.');
class ORM extends Kohana_ORM {
/**
* Set to true if you are creating a new transaction
* Set to false once you commit or rollback.
*
* @author Sigurdur
*/
protected $_transaction_active = false;
/**
* Set the array containing the class and function name in an array
* of the transaction creator.
* Set to null once you commit or rollback.
*
* Example:
* $_transaction_caller = ['class' = 'Model_Tours', 'function' = 'action_set_availability']
*
* @author Sigurdur
*/
protected $_transaction_caller = null;
/**
* Set to true if you are creating a new transaction
* Set to false once you commit or rollback.
*
* @author Sigurdur
*/
protected $_transaction_rollback = false;
/**
* True if a rollback situation is in progress
*
* @author Sigurdur
* @return void
*/
public function begin_transaction()
{
if (!$this->_transaction_active)
{
$backtrace = debug_backtrace(false, 2);
Database::instance()->begin();
$this->_transaction_active = true;
$this->_transaction_rollback = false;
$this->_transaction_caller = ['class' => $backtrace[1]['class'], 'function' => $backtrace[1]['function']];
}
}
/**
* Commits a commit-safe DB transaction
* It is safe to call this function - you will not commit data unless the initial
* calling function is the one who started the transaction.
*
* @author Sigurdur
* @return void
*/
public function commit_transaction()
{
if ($this->_transaction_active)
{
$backtrace = debug_backtrace(false, 2);
if ($this->_transaction_caller['class'] == $backtrace[1]['class'] && $this->_transaction_caller['function'] == $backtrace[1]['function'])
{
Database::instance()->commit();
$this->_transaction_active = false;
$this->_transaction_rollback = false;
$this->_transaction_caller = null;
}
}
}
/**
* Rolls back a commit-safe DB transaction
* It is safe to call this function - you will not commit data unless the initial
* calling function is the one who started the transaction.
*
* Please note that you need to make sure to rollback the transaction from
* the original calling function. Otherwise the transaction is not rolled back.
*
* @author Sigurdur
* @return void
*/
public function rollback_transaction()
{
if ($this->_transaction_active)
{
Database::instance()->rollback();
$this->_transaction_active = false;
$this->_transaction_rollback = true;
$this->_transaction_caller = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment