A caching iterator aggregate designed to wrap a generator and cache its results.
Description
This class allows wrapping a Generator or a callable returning a generator,
caching its values to enable multiple iterations over the same dataset.
Usage Example:
Description
Using a Generator
use FastForward\Iterator\GeneratorCachingIteratorAggregate;
$iterator = new GeneratorCachingIteratorAggregate(
(function () {
yield 'A';
yield 'B';
yield 'C';
})()
);
foreach ($iterator as $value) {
echo $value; // Outputs: A B C
}
foreach ($iterator as $value) {
echo $value; // Outputs: A B C (cached)
}
Description
Using a Callable that Returns a Generator
use FastForward\Iterator\GeneratorCachingIteratorAggregate;
$iterator = new GeneratorCachingIteratorAggregate(fn () => (function () {
yield 1;
yield 2;
yield 3;
})());
foreach ($iterator as $value) {
echo $value; // Outputs: 1 2 3
}
foreach ($iterator as $value) {
echo $value; // Outputs: 1 2 3 (cached)
}
Note: If a callable is provided, it is automatically converted to a generator
using ClosureFactoryIteratorAggregate.
Properties
Methods
Initializes the caching iterator with a generator or a callable returning a generator.
Counts the number of elements exposed by the inner iterator.
Retrieves the iterator, either from the cache or the generator itself.
Initializes the caching iterator with a generator or a callable returning a generator.
public
__construct(
callable|Generator
$generator) : mixed
Description
If a callable is provided, it is wrapped in a ClosureFactoryIteratorAggregate to generate the iterator.
Parameters
$generator
:
callable|Generator
Description
the generator or a callable returning a generator
Counts the number of elements exposed by the inner iterator.
public
count() : int
Description
If the inner iterator implements Countable, this method SHALL return the value provided by that implementation. Otherwise, it MUST count elements by iterating over the iterator. If the inner iterator is not cloneable, this method SHALL wrap the current object in an IteratorIterator instance and count through that wrapper to avoid performing an invalid clone operation. If the inner iterator is cloneable, this method SHOULD count over a clone so that the original iterator state is preserved as much as possible.
Return values
Description
the total number of elements available from the inner iterator
Retrieves the iterator, either from the cache or the generator itself.
public
getIterator() : Traversable
Description
This method ensures that once a generator is iterated, its values remain available for subsequent iterations.
Return values
Description
the cached or fresh iterator