Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^152) CHAPTER 10 ■ SPL ITERATORS
Listing 10-10. Using IteratorIterator and PDOStatement
$db = new PDO('pgsql:dbname=yourdb;user=youruser');
$pdoStatement = $db->query('SELECT * FROM table');
$iterator = new IteratorIterator($pdoStatement);
$limitIterator = new LimitIterator($iterator, 0, 10);
$tenRecordArray = iterator_to_array($limitIterator);
■Note Listing 10-10 is presented just for illustrative purposes. if you want to limit your result set to ten
records, you should use the SQL LIMIT syntax in your SQL query instead.
CachingIterator
Caching iterators are used to perform one-ahead iteration. They are useful when you need to
know, at a given point in the iteration cycle, information about the next element. For example,
you could use this iterator to determine if the current element is the last element in a list. Using
the recursive form, you could decide if a current node is a node or entry in a tree-like structure
by finding out information about the next key.
SeekableIterator
The SeekableIterator is useful for creating nonsequential iteration. It allows you to jump to
any point in the iterator without iterating all previous elements.
NoRewindIterator
The NoRewindIterator is designed for collections that cannot be rewound, or iterated more
than once. This can be useful for iterators that perform a one-time operation during the itera-
tion process, such as inserting a database record.
EmptyIterator
The EmptyIterator is a placeholder iterator and does nothing. It can be useful in certain cases
where an abstract class requires a method to be implemented and return an iterator or when
there is a comparison made between iterators.
InfiniteIterator
The InfiniteIterator is used to continually loop data. Once iteration has found the last element,
the iterator is rewound and begins iterating from the first element again.
McArthur_819-9C10.fm Page 152 Friday, February 22, 2008 9:08 AM

Free download pdf