Forked from miyasinarafat/Basic unit-of-work for Laravel
Created
October 30, 2021 08:12
-
-
Save AhmedHelalAhmed/aa61a91664aa9aee471c9b92f305c2b5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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