If everything goes according to plan (which never is the case), I’ll try and highlight some of the fascinating stuff that can be found inside the SPL. I do a lot of presentations about the SPL, and one of the things I like to tell people is that even though the SPL, - iterators particularly - is a magnificent piece of code that is often underused and misunderstood, it does come with some quirks and glitches that aren’t documented properly.
The SPL is one of hardest things to grasp for most PHP developers. But why is this? The lack of documentation inside the
manual, the fact that there are not many real-life examples, or maybe it’s just too hard? In this post I will try to
explain a bit more about the “iteratorAggregate”
interface. Together with its more famous brother Iterator
, they are currently the two only implementations of the
Traversable
interface, which is needed for objects so they can be used within a standard foreach()
loop. But why and
when should we use the iteratorAggregate
?
Recently, my colleague Jeroen van Dijk needed to extend (or better yet: override) the
accept()* method for the RegexIterator. Turns out this wasn’t as easy as it might sound in practice. So after extending
and overriding multiple methods he found an acceptable solution. But there is room for improvement. And starting from
PHP 5.4, this improvement is available through regexiterator::getregex()
method.
I’ve posted a blog at the @enrise techblog about enhancing SPL’s appenditerator. This lovely iterator can be useful from time to time but it does not always do what you need. Here’s how you can easily create your own iterator: