The Context Library

The Context library provides functionality similar to that of Python’s with-statement contexts.

Installation

1
php composer.phar require "korowai/contextlib:dev-master"

Basic Usage

The library provides with() function, whose typical use is like

1
2
3
4
5
use function Korowai\Lib\Context\with;
// ...
with($cm1, ...)(function ($arg1, ...) {
   // user's instructions to be executed within context ...
});

The arguments $cm1, ... are subject of context management. with() accepts any value as an argument but only certain types are context-managed out-of-the box. It supports most of the standard PHP resources and objects that implement ContextManagerInterface. A support for other already-existing types and classes can be added with Context Factories.

For any instance of ContextManagerInterface, its method enterContext() gets invoked just before the user-provided callback is called, and exitContext() gets invoked just after the user-provided callback returns (or throws an exception). Whatever $cm#->enterContext() returns, is passed to the user-provided callback as $arg# argument.

Simple Example

A relatively popular use of Python’s with-statement is for automatic management of opened file handles. Similar goals can be achieved with the korowai/contextlib and PHP resources. In the following example we’ll open a file to only print its contents, and a resource context manager will close it automatically when leaving the context.

The example requires the function with() to be imported to current scope

1
use function Korowai\Lib\Context\with;

Once it’s done, the following three-liner can be used to open file and read its contents. The file gets closed automatically as soon, as the user callback returns (or throws an exception).

1
2
3
with(fopen(__DIR__.'/hello.txt', 'r'))(function ($fd) {
  echo stream_get_contents($fd)."\n";
});