Created
April 13, 2015 01:26
-
-
Save chrisguitarguy/d449a5506ef4dc23069e to your computer and use it in GitHub Desktop.
A *with* statement in PHP?
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
<?php | |
/* | |
Ideally this would be part of the language: | |
with (createAnObject() as $object) { | |
$object->doStuff(); | |
} | |
This is just sugar for: | |
$object = createAnObject(); | |
$object->enter(); | |
try { | |
$object->doStuff(); | |
} finally { | |
$object->leave(); | |
} | |
This isn't as necessary in PHP which has destructors. If you absolutely need | |
some clean up to run for an object, it can go in `__destruct` | |
*/ | |
interface ContextManager | |
{ | |
public function enter(); | |
public function leave(); | |
} | |
final class ExampleContextManager implements ContextManager | |
{ | |
private $name; | |
public function __construct($name) | |
{ | |
$this->name = $name; | |
} | |
public function enter() | |
{ | |
echo 'Entering Context', PHP_EOL; | |
} | |
public function leave() | |
{ | |
echo 'Leaving Context', PHP_EOL; | |
} | |
public function getName() | |
{ | |
return $this->name; | |
} | |
} | |
function with(ContextManager $context, \Closure $callback) | |
{ | |
$context->enter(); | |
try { | |
call_user_func($callback->bindTo($context)); | |
} finally { | |
$context->leave(); | |
} | |
} | |
with(new ExampleContextManager('Test1'), function () { | |
echo 'Indside Context: ', $this->getName(), PHP_EOL; | |
}); | |
with(new ExampleContextManager('Test1'), function () { | |
throw new \Exception(sprintf('Oops! %s', $this->getName())); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment