HomePHP The Iterator, Countable and ArrayAccess SPL Interfaces
The Iterator, Countable and ArrayAccess SPL Interfaces
In this first part of a short series, I'm going to introduce you to using the Iterator, Countable and ArrayAccess interfaces that come with the Standard PHP Library. You'll see how to implement some of the methods declared by the Iterator interface within a class that manipulates MySQL result sets via an intuitive API.
For many PHP developers eager to apply the object-oriented paradigm in a more thorough and consistent manner, the release of PHP 5 brought a number of handy features that allowed them to achieve this goal in a truly painless fashion. This isn’t breaking news, of course, but the inclusion of member visibility and abstract classes, the support for native exceptions and magic methods, to name just a few examples, gave the language the level of maturity that we see in it these days.
In addition, among the features that were added to PHP 5, there exists the capacity for creating user-defined interfaces. This characteristic permits developers to do programming by contract without too many headaches. However, the support for interfaces doesn’t stop in “userland,” as the language also comes with the Standard PHP Library (SPL). The SPL includes a set of native classes and interfaces that make it easier to tackle common programming problems, such as overloading arrays, traversing directories recursively, and so forth.
Included in the group of native interfaces bundled with the SPL, there are a few that deserve a deeper analysis, as they’re frequently used by many developers nowadays. I’m talking specifically about the Iterator, Countable and ArrayAccess interfaces. When properly implemented, these interfaces allow you to traverse different data collections (e.g. database result sets) by using a simple “foreach” construct, as well as going backward and forward across those data, as when navigating regular arrays.
Given the relevance that these native interfaces have for the average PHP developer, in this series of tutorials I’m going to demonstrate how to use them in the development of a pair of concrete classes, which as you’ll see in a few moments, will act like an abstraction layer for interacting with MySQL.
Now, it’s time to start discovering the actual power behind the Iterator, Countable and ArrayAccess PHP 5 interfaces. Let’s jump in!