Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^146) CHAPTER 10 ■ SPL ITERATORS


Iterators


The SPL provides iterators that are capable of iterating iterators, filtering their data, caching
their results, controlling pagination, and more.

ArrayIterator
The ArrayIterator is probably one of the most versatile iterators in the SPL package. It allows
you to create an iterator from any PHP array. Listing 10-2 shows the creation and use of an iter-
ator from an array.

Listing 10-2. Using an ArrayIterator Iterator

$arr = array('a','b','c');
$iterator = new ArrayIterator($arr);
foreach($iterator as $val) {
echo $val;
}

abc

This might not seem terribly useful here, as you could have skipped the iterator creation
entirely. However, it is important to understand how to manually get an iterator for an array, as
many of the other SPL iterators require an iterator, not an array, to be passed to their constructors.
The ArrayIterator can also save you from needing to directly implement the Iterator
interface’s methods when working with IteratorAggregate classes. If your class uses an array
as the underlying representation, you can simply return an ArrayIterator in getIterator().

LimitIterator
The LimitIterator is one of the simpler iterators. It lets you do the iteration equivalent of SQL
LIMIT and OFFSET, returning a set number of results and defining the index point at which that
set will be taken. The LimitIterator implements the OuterIterator interface.
The LimitIterator’s constructor takes three parameters: an iterator, an offset, and a limit.
Listing 10-3 shows a LimitIterator in use.

Listing 10-3. Using a LimitIterator Iterator

$arr = array(1,2,3,4,5,6,7,8,9);
$arrIterator = new ArrayIterator($arr);
$limitIterator = new LimitIterator($arrIterator, 3, 4);
foreach($limitIterator as $number) {
echo $number;
}

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

Free download pdf