In this third part of a seven-part series on the Iterator, Countable and ArrayAccess SPL interfaces, I give the MySQLi_ResultWrapper class developed in the previous part the capability of counting the number of rows contained in a given result set. I'll do that by implementing the "count()” method declared by the Countable interface. Doing this will make it possible to use an instance of the class to traverse data sets and count records as if they were plain PHP arrays, which is quite appealing to client code that works with the class’s API.
As you possibly know, the Standard PHP Library (also know simply by its acronym, SPL) is comprised of a powerful set of functions, classes and interfaces that permit developers to address problems that occur frequently during the development of web programs. Ranging from autoloading classes on demand and overloading arrays, to recursively traversing directories in the file system, the SPL makes all of these tasks painless.
Among the interfaces included with the library, there are a few that deserve a closer analysis. They can be used to construct classes that allow you to treat distinct data collections as plain PHP arrays. Yes, as this article’s title suggests, in this case I’m talking specifically about the Iterator, Countable and ArrayAccess interfaces. When properly implemented by a class, these interfaces provide it with an intuitive API that can be employed to manipulate text files, database result sets, and so forth by using an array-like notation.
To demonstrate how useful these interfaces can be in a concrete situation, in the two previous parts of this series, I started building a couple of MySQL abstraction classes that performed some common tasks, such as connecting to the database server and running queries, fetching rows and iterating over data sets. I made the last of these classes an implementer of the SPL Iterator interface, which gave it the ability to traverse result sets by way of a simple “foreach()” construct, thanks the implementation of the “rewind(),” “current(),” “key(),” “valid()” and “next()” methods declared by the interface in question.
Although the class in its current state is pretty functional, it lacks an important feature -- it doesn’t implement a method that counts the number of records contained in a given result set. To address this issue, in this third installment of the series I’m going to show you how to make the class an implementer of the Countable interface. Doing this will provide the class with a “count()” method, which naturally will be used for performing the aforementioned counting task in data sets.
Ready to learn a few more useful things about the Countable SPL interface? Then, go ahead and begin reading right away!