Iterators, ArrayAccess, & Countable – Oh My!
Last weekend, I gave a talk on SPL Iterators and Interfaces at MadisonPHP. Beth Tucker Long, our previous Editor in Chief, is one of the main organizers and showed how much she’s contributed to php[tek] (and the planning for php[world]) by putting on a truly excellent regional conference. It was great to see some of the other speakers I’d met previously at php[tek] and meet some other community folks I’d only known online. We all made an effort to meet the attendees, and there were some people working on really interesting things in places that are unfairly overlooked as locations of tech talent.
The talk centered around the real-world use of parts of the SPL for more easily managing of record collections with built-in application logic, such as caching for a database result set. We used that strategy for the Treb framework we built as part of mojoLive: if a cache exists, use it, otherwise get the collection from a database query. I’d also used the SPL for a common interface to queries returned from either a queue or a database in the Social Contest app we wrote.
By adhering to the Iterator
interface, you can simply pass your collection to a foreach
query and consuming code does not have to worry about the underlying implementation for iterating through it. You can further treat your collection like an array by implementing ArrayAccess
: now an individual record can be accessed like $set[3]
. And for further simplicity, you can implement Countable
to simply use the count()
function on your collections instead of exposing a common $set->count()
method.
View the slides here. There are more tips and cool party tricks you can do with the SPL as well as hints for further exploration. To really get the benefit of this often-overlooked part of PHP since version 5, I highly recommend Joshua Thijssen’s Mastering the SPL Library, which I have come to rely on heavily when I’m trying to plumb the rich depths of the SPL.
Finally, if you did see the talk at MadisonPHP, please rate it on Joind.In. I’m always looking for feedback on how I did as a speaker and so I can better help educate PHP developers!
Leave a comment
Use the form below to leave a comment: