Design Patterns PHP - Iterator Java

1) What have we done?

We implemented a default php interface "Iterator"


class ConcreteIterator implements Iterator
{
    /**
     * @var string
     */
    protected $elements;

    private $position = 0;

    function __construct($elements)
    {
        $this->elements = $elements;
    }

    /**
     * (PHP 5 >= 5.0.0)<br/>
     * Return the current element
     * @link http://php.net/manual/en/iterator.current.php
     * @return mixed Can return any type.
     */
    public function current()
    {
        return $this->elements[$this->position];
    }

    /**
     * (PHP 5 >= 5.0.0)<br/>
     * Move forward to next element
     * @link http://php.net/manual/en/iterator.next.php
     * @return void Any returned value is ignored.
     */
    public function next()
    {
        $this->position++;
    }

    /**
     * (PHP 5 >= 5.0.0)<br/>
     * Return the key of the current element
     * @link http://php.net/manual/en/iterator.key.php
     * @return mixed scalar on success, or null on failure.
     */
    public function key()
    {
        return $this->position;
    }

    /**
     * (PHP 5 >= 5.0.0)<br/>
     * Checks if current position is valid
     * @link http://php.net/manual/en/iterator.valid.php
     * @return boolean The return value will be casted to boolean and then evaluated.
     * Returns true on success or false on failure.
     */
    public function valid()
    {
        return isset($this->elements[$this->position]);
    }

    /**
     * (PHP 5 >= 5.0.0)<br/>
     * Rewind the Iterator to the first element
     * @link http://php.net/manual/en/iterator.rewind.php
     * @return void Any returned value is ignored.
     */
    public function rewind()
    {
        $this->position = 0;
    }
}

class Collection
{
    /**
     * @var string[]
     */
    private $elements = [];

    function __construct()
    {
    }

    public function addElement($string)
    {
        $this->elements[] = $string;

        return $this;
    }

    public function removeElement($string)
    {
        if (isset($this->elements[$string]))
            unset($this->elements[$string]);
    }

    /**
     * @return \string[]
     */
    public function getElements()
    {
        return $this->elements;
    }

    public function getCount()
    {
        return count($this->elements);
    }

    /**
     * @return Iterator
     */
    public function createIterator()
    {
        return new ConcreteIterator($this->elements);
    }

}




2) What are pros?

Now we can iterate on "Collection" by "foreach" without accessing whole structure.


$collection = new Collection();
$collection
    ->addElement('a')
    ->addElement('b')
    ->addElement('c')
    ->addElement('d');

$iterator = $collection->createIterator();

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