Datasheet

26
x
CHAPTER 1 INTRODUCING SYMFONY, CAKEPHP, AND ZEND FRAMEWORK
application may display different pages depending on which steps are needed to complete the
transaction.
Context
+request()
State
+handle()
ConcreteStateA
+handle()
state.handle()
ConcreteStateB
+handle()
FIGURE 125: State pattern structure
Iterator
There are many kinds of aggregate objects and many ways to traverse them. One simple example is
an array traversed by consecutive integers supplied to the array operator. To print out a fi ve-element
myArray, you could use the following:
for ($i=0;$i<=4;$i++) {
echo $myArray[$i];
}
However, this solution is not at all elegant. First of all, you have to take care of i variable values.
PHP is not C/C++, so it is not catastrophic to call for
myArray[100] here — it will not return
random trash from memory. However, it is still easy to skip some values with hard-wired ranges.
Another problem is that such an approach exposes the underlying representation of this aggregation.
It makes the traversal procedure dependent on this speci c representation and thus is not reusable.
Object-oriented programming aims to encapsulate the internal structure of aggregate objects and
provide a uniform, safe, and useful interface like this one provided by PHP:
interface Iterator{
function current(); // Returns the value of element under current key
function key(); // Returns the current key
function next(); // Moves the internal pointer to the next element
function rewind(); // Moves the internal pointer to the first element
function valid(); // Returns true if the element under current key is valid
}
Now every class implementing this interface can use the foreach structure. The following snippet of
code produces the same output as the previous
for loop:
foreach ($myArray as $value) {
echo $value;
}
The abstraction behind this mechanism is the Iterator design pattern, pictured in Figure 1-26. The
Client application has access to two abstract classes: Collection, which is the aggregate object
interface, and
TraversalAbstraction, which is created by a corresponding Collection. The
underlying concrete collections can be as different as a List and a Map, yet corresponding methods
c01.indd 26c01.indd 26 1/24/2011 5:45:21 PM1/24/2011 5:45:21 PM