Created
August 23, 2015 19:18
-
-
Save progmars/a064cd89f10550f57266 to your computer and use it in GitHub Desktop.
This file contains 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
Could you provide a code snippet on how to use it, let's say to update one record?
I use the unit of work in Entity Framework but i don't quite understand how to use this one, thanks!