In this second part of a series, I make the MySQLi_ResultWrapper class a full implementer of the Iterator SPL interface. Implementing the rest of the methods declared by the interface is a straightforward process that allows us to traverse MySQL result sets by using a plain “foreach” construct.
As you may know, the Standard PHP Library (commonly know as SPL) provides developers with a powerful set of native classes and interfaces that can be used for easily tackling problems that come up in everyday programming, such as autoloading resources on request, traversing recursively directories, overloading arrays, and so forth.
Due to the huge extension of the SPL, I don't intend to cover in depth each of these classes and interfaces. You can read the PHP manual to get a more intimate background on them, or even pick up a good book that discusses the library from the basics to its most complex facets.
There are, however, some components included with the SPL that can be extremely useful in multiple scenarios and environments, which can be analyzed in detail without a degree in rocket science. That’s exactly the case with the Iterator, Countable and ArrayAccess interfaces. When used together, they allow programmers to build implementer classes that permit one to iterate over different data collections, such as file rows and database result sets, and manipulate them as if they were plain arrays.
To demonstrate how useful these interfaces can be, in the introductory part of this series I started developing a couple of MySQL abstraction classes. The first one was tasked with connecting to the server and running queries, and the second one was charged with handling data sets in different ways. I made the latter an implementer of the Iterator interface, which will allow us to traverse database rows by using simply a “foreach” construct.
Well, to be frank, this last class implemented only a part of the methods declared by Iterator. This issue must be properly addressed. Thus, in this second episode of the series I’m going to finish implementing the remaining methods defined by the Iterator interface, a process that hopefully will give you a clear idea of how to use it in a real-world context.
Ready to learn more about the handy Iterator, Countable and ArrayAccess SPL interfaces? Then click on the link below and read the next few lines!