Lab 04: Generators Advanced

Time: 40 minutes | Level: Advanced | Docker: docker run -it --rm php:8.3-cli bash

Generators produce values lazily — one at a time — dramatically reducing memory usage for large datasets. Advanced features include yield from delegation, bidirectional communication via send(), and lazy transformation pipelines.


Step 1: Generator Basics Recap

<?php
function fibonacci(): \Generator {
    [$a, $b] = [0, 1];
    while (true) {
        yield $a;
        [$a, $b] = [$b, $a + $b];
    }
}

$fib = fibonacci();
for ($i = 0; $i < 10; $i++) {
    echo $fib->current() . ' ';
    $fib->next();
}
echo "\n";

📸 Verified Output:


Step 2: Generator Delegation — yield from

yield from delegates to another generator, array, or iterable:

📸 Verified Output:

💡 yield from also works with plain arrays: yield from [1, 2, 3]; — keys are preserved.


Step 3: Bidirectional Generators — send()

send() passes a value back into the generator at the yield expression:

📸 Verified Output:


Step 4: getReturn() from Generators

📸 Verified Output:

💡 getReturn() throws a \Error if called before the generator finishes. Always check $gen->valid() === false first.


Step 5: Lazy Evaluation Pipeline

Chain generators for memory-efficient data transformation:

📸 Verified Output:


Step 6: Memory Comparison — Array vs Generator

📸 Verified Output:

💡 Generators use O(1) memory regardless of dataset size. Arrays allocate all memory upfront.


Step 7: Generator-Based File Processing

📸 Verified Output:


Step 8: Capstone — Infinite Data Stream with Windowing

Process a theoretically infinite stream with sliding window aggregation:

📸 Verified Output:


Summary

Feature
Syntax
Use Case

Basic yield

yield $value;

Lazy sequence

Yield key-value

yield $key => $value;

Lazy associative data

Generator delegation

yield from $gen

Compose generators

Yield from return

$val = yield from $gen;

Capture sub-generator return

Bidirectional

$x = yield 'out'; $gen->send('in')

Push values into generator

Return value

return $val; + $gen->getReturn()

Final aggregated result

Lazy pipeline

Chain generator functions

Memory-efficient ETL

Memory benefit

O(1) vs O(n)

1000x+ less memory for large data

Last updated