PHP added generators in version 5.5. You see them in code with the yield
keyword and they tend to be used most often to iterate over a collection dynamically without creating it in memory all at once. Really you can do all sorts of fun things with generators that we’re not going to touch here.
IteratorAggregate has been around forever — since PHP 5.0. It’s a way to make an object traversable (able to be used in a foreach
loop) without having to implement all the methods of Iterator. IteratorAggregate
also makes it possible to do nested loops on the same object.
A powerful combination is to use a generator within your IteratorAggregate::getIterator
implementation. Rather than returning a new iterator object each time, just supply a generator. Here’s a small example.
And it’s usage:
This is an extremely powerful pattern when you need to iterate over collections with some form of known computation mixed in. Our recently released CSV library does this to produce associative arrays from a CSV file.
Something more dynamic would be better suited to a generic map
implementation.