DEV Community

Cover image for introducing PHP custom collections with the `IteratorAggregate` interface
yactouat
yactouat

Posted on • Updated on

introducing PHP custom collections with the `IteratorAggregate` interface

Hi there !

In the previous article of this small series about PHP iterators and generators, we mentioned that you often wont need to create custom iterators for your day-to-day tasks as PHP provides predefined iterators that will make your life easier.

However, sometimes the logic of your code may be very domain specific and the objects you're using might in fine be very custom, and it makes sense in such situations to loop over that collection of objects in a specific way. This is a good use-case for a collection of objects. Now let's create one with PHP !

A collection is a custom iterable object that holds a list, often case an array, in it. This is that list that is then traversed according to the rules that you have set up using the IteratorAggregate interface.

A class with that interface must implement:

  • a constructor, in which we would pass raw data as an array, or an Iterator, when we instantiate it
  • the getIterator method

Using this interface on a class would result in defining an external iterator as this class would need to be attached another iterator to provide some iteration logic to it. Feeling confused ? dont worry it did that to me too.

Let's make that more human-readable with an example:

Now, you know enough to create your own custom collections, I used FilterIterator here for this collection iterator, but feel free to leverage the possiblities of the other PHP iterators out there as you see fit ! You can even spice things up using an iterator of your own to use alongside our collection.

Until then 👋

Top comments (0)