2017 © Pedro Peláez
 

library scope-guard

ScopeGuard provides a better way to structure transactions and rollbacks

image

scope-guard/scope-guard

ScopeGuard provides a better way to structure transactions and rollbacks

  • Wednesday, October 12, 2016
  • by Erikvv
  • Repository
  • 1 Watchers
  • 1 Stars
  • 28 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 1 Versions
  • 0 % Grown

The README.md

composer require scope-guard/scope-guard dev-master

ScopeGuard for PHP

This is a PHP implementation of the ScopeGuard idiom., (*1)

You can use this whenever you want to schedule code to run on the end of a scope. If you are already mainly using exceptions the readability of some pieces of code can improve greatly., (*2)

You can differentiate between code that should be executed * always (onExit) * when the scope is left early through an exception or early return (onFailure) * when the scope is left sucessfully (onSuccess), (*3)

Simplest example

This closes a connection on scope exit., (*4)

use ScopeGuard\Scope;

$connection = connect() 
$scope = new Scope;
$scope->onExit([$connection, 'disconnect']);

/* do stuff with $connection */

/* explicit or implicit return, ->disconnect() is called here */
return;

OnFailure example

use ScopeGuard\Scope;

$salesEntry = new SalesEntry;

$scope = new Scope;
$scope->onFailure(function use ($serviceDesk, $salesEntry) { $serviceDesk->alertRepresentative($salesEntry); }); 

/* more logic here */

// this makes sure any success handlers are called. 
// any other path leads to the failure handlers being called
$scope->markSuccessful(); 

// unset can manually trigger the handlers (taking into account the regular reference-counting semantics)
unset($scope);

Probably you will find onFailure the most useful for doing rollbacks, attaching more handlers as the script progresses, and entering the failure flow by throwing an exception., (*5)

OnSuccess will generally not be used because your normal code is the success case, but it may help to group some statements more logically., (*6)

OnExit can be used for something like cleanup which must be done regardless of what the eventual outcome of the script was., (*7)

It is perfectly fine to use multiple Scope object at the same time., (*8)

The Versions

12/10 2016

dev-master

9999999-dev

ScopeGuard provides a better way to structure transactions and rollbacks

  Sources   Download