Download the PHP package ehough/generators without Composer
On this page you can find all versions of the php package ehough/generators. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download ehough/generators
More information about ehough/generators
Files in ehough/generators
Package generators
Short Description Simulate generators in PHP 5.3 and 5.4. Useful for backporting code.
License MPL-2.0
Informations about the package generators
ehough/generators
Easily backport generators to PHP 5.3 and 5.4.
ABANDONED
The vast majority of PHP installations now natively support generators, so this library is obsolete.
Why?
This library makes it (relatively) easy to backport code that relies on generators for use on legacy (PHP < 5.5) systems. If you don't need to backport code to PHP 5.3 or 5.4, you don't need this library.
Quick Start
Say you need to use the following code on PHP 5.3:
The above code results in:
Since the code above uses generators, it won't run on PHP 5.4 or lower. This library provides you with the AbstractGenerator
class, which requires you to implement resume($position)
. $position
is incremented each time the generator resumes execution, and you can use the position to determine which part of the generator to run. So the above generator could be rewritten as:
The above code results in:
The code is not nearly as clean and simple, but any generator can be rewritten using this library.
Yielding Keys and Values
You have three choices for what you return from resume($position)
:
- If you return null, you are signaling that there are no more statements inside the generator. The generator will be considered to be closed at this point.
- If you return an array with two values, the first element is interpreted to be the yielded key and the second value is the yielded value.
- If you return an array with one value, it is interpreted to be a yielded value, and
$position
will be used as the key.
Accessing Sent Values
You can access the last value sent in from the caller with getLastValueSentIn()
. This might be null
.
Handling Exceptions
By default, if an exception is thrown into the generator (via throw(\Exception $e)
) it will be rethrown back to the calling context. If you'd like to "catch" these exceptions, you can override onExceptionThrownIn(\Exception $e)
and swallow or otherwise handle the exception.