Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 10 ■ SPL ITERATORS^161

Just the Facts


This chapter covers SPL iterators, which can be an elegant solution to complex programming
challenges.
To control looping of objects using foreach, your classes must implement the Traversable
interface. You cannot directly implement Traversable; you must implement it through either the
Iterator or IteratorAggregate interface. Iterator requires you to implement all the iteration
methods. IteratorAggregate allows you to offload those methods to another class. As an example,
you saw how to use the built-in ArrayIterator to iterate an array-based collection without imple-
menting anything more than the getIterator() method described in IteratorAggregate. The SPL
also includes more complicated iterator interfaces like RecursiveIterator, OuterIterator, and
SeekableIterator.
The SPL provides a selection of iterator classes that implement the iterator interfaces
and that solve common programming challenges. Of particular note are the ArrayIterator,
LimitIterator, FilterIterator, and RegexIterator iterators, as well as their recursive forms.
The final section of this chapter presented examples of using iterators to solve common prob-
lems. The SimpleXMLIterator, included with the SimpleXML extension, is a RecursiveIterator
that allows you to use XML files by looping through elements one at a time. The DbaReader and
IniGroups iterators, included in the DBA extension, are useful for parsing files, such as .ini files.

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

Free download pdf