Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
143

■ ■ ■


CHAPTER 10


SPL Iterators


As you learned in the previous chapter, in order to control looping with the foreach state-
ment, all objects must implement the Traversable interface. But, the Traversable interface is
an internal-only interface, so trying to implement it in your userland classes will simply result
in an error. To actually implement looping of your objects, you must implement Traversable
via the Iterator or IteratorAggregate interface.
For some uses, implementing Iterator might be enough, but when you need more func-
tionality, you can choose from several extended iterator interfaces, which allow for seekable,
recursive, aggregated, or even cached access.
Along with providing the capability to iterate objects, the SPL also contains a number of
advanced iterator algorithms for filtering, searching, comparing, and integrating with the most
popular PHP data-access methods.
In this chapter, you will learn about the iteration interfaces and classes that the SPL provides.
The examples in this chapter are highly dependent on your PHP environment. If you plan to
use the SPL in your development, PHP version 5.2.1 or higher is recommended.

Iterator Interfaces and Iterators


The SPL iterator interfaces are designed to help you implement advanced iteration algorithms,
allowing you to create elegant data-access methods for your classes. These interfaces form the
basis for creating iterator classes. You could go ahead and create your own iterators from these
interfaces; however, the SPL extension defines an ever-growing number of built-in iterator
classes to tackle the most common iteration tasks. Let’s look at the interfaces, and then review
some of the built-in classes.

Iterator Interfaces.


The SPL provides five iterator interfaces: Traversable, Iterator, IteratorAggregate,
OuterIterator, and RecursiveIterator. These are described in the following sections.

Traversable
The Traversable interface isn’t really an interface as much as it is an attribute. This is because
only internal classes—those written in C code—may implement Traversable directly. Any
userland class that needs to implement Traversable must do so by implementing one of the
userland interfaces that descend from Traversable.

McArthur_819-9C10.fm Page 143 Friday, February 22, 2008 9:08 AM

Free download pdf