Custom Context Managers¶
A custom context manager can be created by implementing the
ContextManagerInterface
. The new context
manager class must implement two methods:
enterContext()
: the value returned by this function is passed as an argument to user-provided callback when usingwith()
,exitContext()
: the function accepts single argument$exception
of typeThrowable
, which can benull
(if no exception occurred within a context); the function must return boolean value indicating whether it handled (true
) or not (false
) the$exception
.
Simple Value Wrapper¶
In the following example we implement simple context manager, which wraps a
string and provides it as an argument to user-provided callback when using
with()
. Note, that there is a class
TrivialValueWrapper
for very similar purpose
(except, it’s not restricted to strings and it doesn’t print anything).
Import symbols required for this example
1 2 | use Korowai\Lib\Context\ContextManagerInterface;
use function Korowai\Lib\Context\with;
|
The class implementation will be rather simple. Its enterContext()
and
exitContext()
will just print messages to inform us that the context was
entered/exited.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class MyValueWrapper implements ContextManagerInterface
{
protected $value;
public function __construct(string $value)
{
$this->value = $value;
}
public function enterContext()
{
echo "MyValueWrapper::enter()\n";
return $this->value;
}
public function exitContext(?\Throwable $exception = null) : bool
{
echo "MyValueWrapper::exit()\n";
return false; // we didn't handle $exception
}
}
|
The new context manager is ready to use. It may be tested as follows
1 2 3 | with(new MyValueWrapper('argument value'))(function (string $value) {
echo $value . "\n";
});
|
Obviously, the expected output will be
1 2 3 | MyValueWrapper::enter()
argument value
MyValueWrapper::exit()
|