In this fourth part of a six-part series, that covers the Iterator, Countable, and ArrayAccess SPL interfaces, I show how to partially implement the methods declared by the ArrayAccess SPL interface within a sample class that manipulates MySQL result sets.
This isn't breaking news certainly, but as you may have heard, PHP 5 comes packaged with a powerful set of functions, classes and interfaces commonly know as the Standard PHP Library (SPL), which can be used for tackling typical problems present in day-to-day programming without having to reinvent the wheel every time. As with other features offered by the language, some of these classes and interfaces are more appealing than others to developers. That's exactly the case with the Iterator, Countable and ArrayAccess interfaces, which when implemented in a clever way, allow you to treat several data collections as if they were plain array elements.
To show how the interfaces in question can be used in a real-word example, in the tutorials that preceded this one I started building a couple of MySQL abstraction classes. The first one was tasked with connecting to the database server and running queries, and the second class was responsible for fetching and manipulating result sets via a simple API.
The latter, which was a basic wrapper for the "MySQLi" native class bundled with PHP 5, implemented two of the interface mentioned above, that is the Iterator and Countable respectively. This meant the class could traverse rows in data sets by way of a "foreach" construct, and also count them by using a "count()" method, in a very similar array notation.
It should be admitted, though, that the current functionality of this sample MySQLi wrapper class could be easily enhanced by implementing the ArrayAccess SPL interface. This would allow you to fetch different rows in a given result set by specifying only their offset. That sounds quite interesting, right? Since ArrayAccess declares four methods, in this article I'm going to show you how to implement several (though not all) of those methods within the mentioned class, in this way making it slightly more functional.
Ready to learn the full details of this implementation process? Then start reading right now!