Skip to content

Instantly share code, notes, and snippets.

@progmars
Created August 23, 2015 19:18
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save progmars/a064cd89f10550f57266 to your computer and use it in GitHub Desktop.
Save progmars/a064cd89f10550f57266 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();
@stesvis
Copy link

stesvis commented Jan 29, 2019

Could you provide a code snippet on how to use it, let's say to update one record?

  • fetch the record
  • update
  • save

I use the unit of work in Entity Framework but i don't quite understand how to use this one, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment