BehavioralPHPverifiedVerified

Iterator Pattern in PHP

Provides a way to sequentially access elements of a collection without exposing its underlying representation.

How to Implement the Iterator Pattern in PHP

1Step 1: Define an iterable collection using PHP's built-in iterator interface

class NumberRange implements \Iterator
{
    private int $current;

    public function __construct(
        private readonly int $start,
        private readonly int $end,
    ) {
        $this->current = $start;
    }

    public function current(): int { return $this->current; }
    public function key(): int { return $this->current - $this->start; }
    public function next(): void { $this->current++; }
    public function rewind(): void { $this->current = $this->start; }
    public function valid(): bool { return $this->current <= $this->end; }
}

2Step 2: Use the iterator with foreach

$range = new NumberRange(1, 5);

foreach ($range as $index => $value) {
    echo "Index {$index}: {$value}\n";
}

3Step 3: Demonstrate a generator-based iterator

function fibonacci(int $limit): \Generator
{
    $a = 0;
    $b = 1;
    for ($i = 0; $i < $limit; $i++) {
        yield $a;
        [$a, $b] = [$b, $a + $b];
    }
}

foreach (fibonacci(10) as $num) {
    echo "{$num} ";
}

Iterator Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Iterator Pattern in the Real World

Think of a TV remote control. Whether your playlist is on a Blu-ray disc, a streaming service, or a USB drive, you use the same next and previous buttons to cycle through content. The remote (iterator interface) abstracts away the completely different internal mechanisms each media source uses to retrieve the next item.