The fun side of outer iterators (at least when using an OOP approach) is that their implementation is (in most cases) a straightforward process that can be mastered in a snap. Of course, claming this without concrete proof would be rather pointless. In line with this idea, in previous installments of this series I went through the development of a couple of concrete examples that demonstrated how to use an external iterator for traversing the protected fields of a class whose primary use was to model generic entities. In the first tutorial, the whole traversing task was performed via a custom array collection, while the second how-to achieved the same process through the native ArrayIterator class bundled with the SPL. In both cases, the results were nearly identical, even though the use of a built-in class like ArrayIterator, saved us from the hassles of having to write an array wrapper all by ourselves. You find both tutorials here: External Iterators in PHP Using OOP and External PHP Iterators using the ArrayIterator Class respectively. It goes without saying that external iterators can be used for many different purposes, aside from those described above. What’s more, they can be utilized not only for traversing structures, but for lazy-loading data as well. If you’re wondering how this can be achieved, I’ll be building a simple file helper class, which will be responsible for reading/writing data to a specified text file in the following sections. The “beauty” of this helper is that it will be able to lazy-load the data written to the pertaining file through the same array collection that you saw in the preceding tutorials. Traversing Array Elements: Building a Custom Array Collection As stated in the introduction, the file helper that I plan to build in the following sections will use an external iterator to lazy-load the data saved to a given text file. In this particular case, I’ll be somewhat lazy too since the iterator employed by the helper in question will be the same custom array collection implemented in earlier chapters of this series. In case that this collection doesn’t ring any bells to you, here it is again for your perusal:
Pretty simple right? As seen above, the “ArrayCollection” class is nothing but a simple wrapper for plain PHP arrays, which permits us to iterate over its elements, count them, and set/unset them as well. In the following section I’ll be building the aforementioned file helper class, which will use the earlier array collection for lazy-loading the data written to a specific file.
blog comments powered by Disqus |