Skip to content

Instantly share code, notes, and snippets.

@dadamssg
Last active December 26, 2015 05:39
Show Gist options
  • Save dadamssg/7101978 to your computer and use it in GitHub Desktop.
Save dadamssg/7101978 to your computer and use it in GitHub Desktop.
<?php
abstract class TransactionHelper {
protected $closures = [];
public function add(Closure $closure)
{
$this->closures[] = $closure;
}
public function empty()
{
$this->closures = [];
}
public function flush()
{
if ($this->transact()) {
$this->empty();
}
}
abstract public function transact();
}
class EloquentTransactionHelper extends TransactionHelper {
public function transact()
{
DB::transaction(function()
{
foreach ($this->closures as $closure) {
$closure();
}
return true;
});
return false;
}
}
class DoctrineTransactionHelper extends TransactionHelper {
public function transact()
{
foreach ($this->closures as $closure) {
$closure();
}
return true;
}
return false;
}
class PropelTransactionHelper extends TransactionHelper {
public function transact()
{
if ! empty($this->toSave) {
$con = Propel::getConnection(MyApp::DATABASE_NAME);
$con->beginTransaction();
try {
foreach ($this->closure as $closure) {
$closure();
}
$con->commit();
return true;
} catch (Exception $e) {
$con->rollback();
throw $e;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment