Skip to content

Instantly share code, notes, and snippets.

@meglio
Created August 17, 2011 22:49
Show Gist options
  • Save meglio/1152843 to your computer and use it in GitHub Desktop.
Save meglio/1152843 to your computer and use it in GitHub Desktop.
Cancellable and transactionable behaviors for PHP
<?php
namespace core\utils;
/**
* @throws \Exception
* @param mixed $prepare
* @param mixed $doJob
* @param mixed $finalize
* @param mixed $cancel
* @return mixed
*/
function doCancellable($prepare, $doJob, $finalize, $cancel)
{
$prepare();
try
{
$result = $doJob();
$finalize();
return $result;
}
catch(\Exception $e)
{
$cancel();
throw $e;
}
}
/**
* @param \PDO $pdo
* @param $job
* @return \core\orm\Market
*/
function doInTransaction(\PDO $pdo, $job)
{
return doCancellable(
function() use($pdo) { /** @var \PDO $pdo */ $pdo->beginTransaction(); },
$job,
function() use($pdo) { /** @var \PDO $pdo */ $pdo->commit(); },
function() use($pdo) { /** @var \PDO $pdo */ $pdo->rollback(); }
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment