Skip to content

Files

Latest commit

b8aa050 · Sep 27, 2023

History

History
This branch is 5 commits behind DesignPatternsPHP/DesignPatternsPHP:main.

Iterator

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Oct 1, 2021
Aug 19, 2019
Oct 1, 2021
Apr 25, 2023
Sep 27, 2023

Purpose

To make an object iterable and to make it appear like a collection of objects.

Examples

  • to process a file line by line by just running over all lines (which have an object representation) for a file (which of course is an object, too)

Note

Standard PHP Library (SPL) defines an interface Iterator which is best suited for this! Often you would want to implement the Countable interface too, to allow count($object) on your iterable object

UML Diagram

Alt Iterator UML Diagram

Code

You can also find this code on GitHub

Book.php

.. literalinclude:: Book.php
   :language: php
   :linenos:

BookList.php

.. literalinclude:: BookList.php
   :language: php
   :linenos:

Test

Tests/IteratorTest.php

.. literalinclude:: Tests/IteratorTest.php
   :language: php
   :linenos: