Setting the Table
I tend to think in structural terms to address a given task. I need an object to do “X” and another object to do “Y.” This is in contrast to sequential and procedural thinking; first I’ll do this, and then I’ll do that, and then another thing. Structural thinking is easier on my brain, and it’s a lot easier to make changes and add updates. When it comes to the process of sequentially accessing the elements of an aggregate object (some kind of list), I don’t think of a sequential process, I think of an Iterator design pattern. The Iterator contains both aggregate and iterator objects. That makes it much clearer. Common PHP tasks include iterating through a MySql table. Sometimes MySql table elements are passed to PHP arrays or even XML files. Further, some lists are optimized for searching, such as linked lists and skip lists. We’ll get to those in future posts regarding the Iterator design pattern. However, in PHP, sequential storage outside of a MySql table is typically a numeric or associative array. At this point the focus is on plain vanilla lists stored in aggregate objects we call arrays. Before getting further into this topic, Play the sample and Download the code for an overview:
According to the Gang of Four, the key idea in the Iterator
is to take the responsibility for access and traversal out of the list object and put it into an iterator object.
Typically, iterating through a list involves something like the following:
< ?php class StandardIteration { public function __construct() { $bigList=array('rupiah','peso', 'real', 'rupee', 'dollar', 'euro', 'yen', 'pound', 'yuan', 'dinar', 'shekel', 'krone', 'ringgit', 'rial', 'shilling', 'rand', 'ruble', 'dong'); $counter=0; echo "World Currency List |
The “list” of elements reside in an array, and using a looping structure, programs can sequentially access all or some of the elements.
Access

Figure 1: Access through a Sequence

Figure 2: Binary tree access
Continue reading ‘PHP Iterator Design Pattern I: Access to Aggregates’
Recent Comments