Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^144) CHAPTER 10 ■ SPL ITERATORS
Two base-level classes descend from Traversable and are accessible to your objects:
Iterator and IteratorAggregate. By implementing one of these two interfaces, an object may
be used with the foreach statement.
Iterator
The Iterator interface was introduced in the previous chapter. Its primary purpose is to allow
a class to implement a basic iteration where it can be looped, keys accessed, and rewound. As
a reminder, it contains five methods: rewind(), current(), key(), next(), and valid().
IteratorAggregate
The IteratorAggregate interface is used to offload the five iteration methods required by
Iterator onto another class. This lets you make iteration external to the class and allows you to
reuse common iteration methods instead of repeating them inside each iterable class you write.
The IteratorAggregate interface, if it were written in PHP, would have the following
definition:
interface IteratorAggregate extends Traversable {
function getIterator();
}
The getIterator() method, when implemented, must return an instance of a class that
implements Iterator. Typically inside getIterator(), you will pass class information to the
constructor of a specialized iteration class. This data might be an underlying array, or any other
data that you can conceive of, as long as it is sufficient to control the five Iterator methods.
The SPL provides a few built-in iterators that are designed for use with the
IteratorAggregate interface. Using these iterators will mean that you need to implement only
one method and instantiate a single class to make your object iterable. Listing 10-1 shows the
use of the ArrayIterator with the IteratorAggregate interface. ArrayIterator and the other
built-in iterators are discussed in more detail in the “Iterators” section later in this chapter.
Listing 10-1. Using the IteratorAggregate Interface
class MyIterableClass implements IteratorAggregate {
protected $arr;
public function __construct() {
$this->arr = array(1,2,3);
}
public function getIterator() {
return new ArrayIterator($this->arr);
}
}
foreach(new MyIterableClass() as $value) {
echo $value. "\n";
}
McArthur_819-9C10.fm Page 144 Friday, February 22, 2008 9:08 AM

Free download pdf