Generators for lazy evaluation: practical patterns in PHP
Generators are one of the most underused features in PHP. Beyond file reading, they have several useful patterns.
Infinite sequence (no memory growth):
Pipeline: compose multiple transforms without intermediate arrays:
The pipeline pattern is genuinely useful for ETL-style data processing. Each step is testable in isolation, memory usage stays flat, and adding a new transform is one function.
yield from delegates to another generator or iterable. Useful for recursive generators (tree traversal) where you would otherwise need to collect all results before yielding them.
Generators do not rewind by default. Once exhausted they cannot be iterated again. If you need to iterate multiple times, collect into an array or create a new generator instance.
Send values into a generator with $gen->send($value). The send value becomes the return value of yield inside the generator. Useful for two-way communication in coroutine patterns.
return inside a generator terminates it and the return value is accessible via $gen->getReturn() after the generator is exhausted. Useful for aggregation: yield individual items, return the final count.
```php blocks are runnable.