*Why do we even need Iterator patterns?*

105 views Asked by At

So I lean back all relaxed and sh*t, refurbishing my design patterns knowledge, everything going fine and dandy, as I wait for the weekend adrenaline to kick in. My life couldn't get any smoother. Next thing you know... I get the biggest realization of my life day.

Why do we need Iterator Pattern? Or better phrased as

Do we even need Iterator Pattern in today's age?

Since I'm a native PHP speaker. No-brainer, I was going through this official DOC.

So through various Rube Goldberg-ish examples in the comments, the pattern goes on to create various objects passing an array to them, only to eventually iterate over the items using foreach() or a while() so my question is where in the grand scheme of things does this pattern fit in, Or couldn't we have been better off just iterating over the array itself in the first place or as always ....

Am I missing something?

Example:

<?php
class myIterator implements Iterator 
    {
    private 
        $_array = array();
    public function __construct(array $array) 
        {
        $this->_array = $array;
        }
    public function rewind() 
        {
        reset($this->_array);
        }
    public function current() 
        {
        return current($this->_array);
        }
    public function key() 
        {
        return key($this->_array);
        }
    public function next() 
        {
        next($this->_array);
        }
    public function valid() 
        {
        return $this->key() !== null;
        }
    }

$it = new myIterator(array('foo_1' => 'bar_1','foo_2' => 'bar_2'));

//example 1 : foreach

foreach($it as $key => $value) 
    {
    var_dump($key, $value);
    }

//example 2 : while

$it -> rewind();
while($it->valid())
    {
    var_dump($it->key(), $it->current());

    $it->next();
    }

//example 3 : for

for($it->rewind();$it->valid();$it->next())
    {
   var_dump($it->key(), $it->current());
    }
?>
0

There are 0 answers