Created
July 26, 2011 09:31
-
-
Save sunaot/1106368 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
<?php | |
// see https://gist.github.com/1106254 about toClosure() function. | |
class SpecificException extends Exception {}; | |
class Sample | |
{ | |
// Exectute Around Method and try-catch-finally sample in PHP. | |
function inLock($callback) { | |
$unlock = \toClosure(get_class(), 'unlock', $this); | |
$ensure = function() use($unlock) { $unlock(); }; | |
$this->lock(); | |
try { | |
$callback(); | |
$ensure(); | |
return; | |
} catch (SpecificException $e) { | |
// rescue specific case | |
$ensure(); | |
return; | |
} catch (Exception $e) { | |
$ensure(); | |
throw $e; | |
} | |
throw new Exception('you cannot be here.'); | |
} | |
function lock() { | |
echo "lock", PHP_EOL; | |
} | |
function unlock() { | |
echo "unlock", PHP_EOL; | |
} | |
} | |
function usage() { | |
$obj = new Sample; | |
$obj->inLock( | |
function() { | |
echo "during execution", PHP_EOL; | |
} | |
); | |
} | |
usage(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment