Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AhmedHelalAhmed/aa61a91664aa9aee471c9b92f305c2b5 to your computer and use it in GitHub Desktop.
Save AhmedHelalAhmed/aa61a91664aa9aee471c9b92f305c2b5 to your computer and use it in GitHub Desktop.
Simple contract or interface, call as you wish:
interface UnitOfWork
{
public function begin();
public function commit();
public function rollback();
}
Implementation for database with preventing nested commits/rollbacks:
class UnitOfWork implements UnitOfWorkInterface
{
private $inTransaction = false;
private static $runningTransactions = 0;
public function begin()
{
if(static::$runningTransactions > 0){
return $this;
}
// nothing to do, will not start nested transaction
$this->inTransaction = true;
static::$runningTransactions++;
\DB::beginTransaction();
return $this;
}
public function commit()
{
if(!$this->inTransaction){
return $this;
}
\DB::commit();
$this->inTransaction = false;
static::$runningTransactions--;
return $this;
}
public function rollback()
{
if(!$this->inTransaction){
return $this;
}
\DB::rollBack();
$this->inTransaction = false;
static::$runningTransactions--;
return $this;
}
function __destruct()
{
// rollback if not committed
if($this->inTransaction){
$this->rollback();
}
}
}
Facade for Laravel:
class UnitOfWork
{
public static function instance()
{
return app()->make(\App\Services\Contracts\UnitOfWork::class);
}
}
And using it like this:
$uow = UnitOfWork::instance()->begin(); // UnitOfWork should point to facade here
// ... lots of code, maybe with inner calls to UnitOfWork::instance, which would do nothing because of nesting counters
$uow->commit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment