HomePHP Implementing More Methods of the ArrayAccess SPL Interface
Implementing More Methods of the ArrayAccess SPL Interface
In this fifth part of a six-part series on the Iterator, Countable and ArrayAccess SPL interfaces, I implement the rest of the methods declared by the ArrayAccess SPL interface within the “MySQLi_ResultWrapper” class that you saw in a previous part. Once this process is completed, the class will be able to treat records in database result sets as if they were plain array elements.
If you’re a PHP developer who frequently builds object-oriented web applications, then it’s possible that you’ve already worked with user-defined interfaces. PHP 5 offers strong support for them, among the numerous features that make up its highly-enhanced object model.
However, the support for interfaces doesn’t stop in the so-called “userland.” The language comes with a decent number of native interfaces for building implementing classes that perform all sorts of clever tasks, such as overloading arrays, iterating recursively over directories in the file system, and so forth.
Included with these native interfaces that are part of the Standard PHP Library (SPL), there are a few that deserve an in-depth analysis. They're very popular with many PHP programmers, especially for developing flexible database access layers. In this particular case, I’m talking about the Iterator, Countable and ArrayAcccess native interface. When used properly, they permit developers to create implementing classes that not only exploit the intrinsic benefits of Polymorphism, but allow them to overload arrays in a pretty painless fashion.
Of course, if you’ve been a loyal reader and have already read all of the articles that precede this one, then at this point you have a clear idea of how to implement the aforementioned interfaces within a real-world class. In those tutorials I started developing one that was tasked with manipulating MySQL result sets via a simple API. The class in question implemented the methods defined by the Iterator and Countable SPL interfaces respectively, which gave it the ability to traverse database record sets by using a plain “foreach” construct, as well as count the number of rows contained in those sets.
In addition, two of the methods declared by the ArrayAccess interface were included in the definition of this sample MySQL abstraction class, in this way extending its existing functionality even further. As you possibly know, though, any class implementing a given interface must include (and in most cases, implement) all of the methods that the interfaces define.
In order to meet this requirement, in this fifth chapter of the series I’m going to finish implementing the remaining methods of the ArrayAccess interface within the MySQL abstraction class built previously. Now, let’s learn more about the ArrayAccess interface. Let’s go!