assessmentee.com

Home | Start test | Contact
 

Activerecord | Adapter | Decorator | DependencyInjectionContainer | Facade | Factory | Hydration | Inheritance | Iterator | Mapper | MVC | Observer | Prototype | Proxy | Registry | ServiceLocator | Singleton | Specification | Strategy | TableGateway | ZF1_TableGateway | ZF2_TableGateway |




    <?php
/*
 * iterator design pattern
 * Iterate through a stack of objects as if they are arrays
 */

class Vegetable {

    protected $name;
    protected $color;

    public function __construct($name,$color) {
        $this->name = $name;
        $this->color = $color;
    }

    public function getInfo() {
        return $this->name . ' ' . $this->color.'<br />';
    }

}

class ShoppingList {

    protected $list = array();

    public function add($item) {
        array_push($this->list, $item);
    }

    public function getCount() {
        return count($this->list);
    }

    public function getList() {
        return $this->list;
    }

}

class ShoppingListIterator {

    protected $list;
    protected $counter = 0;

    public function __construct($list) {
        $this->list = $list;
    }

    public function hasNextItem() {
        if ($this->list->getCount() > $this->counter) {
            return true;
        }
    }

    public function next() {
        $list = $this->list->getList();
        $this->counter++;
        return $list[$this->counter - 1];
    }

}

$shoppingList = new ShoppingList();
$shoppingList->add(new Vegetable('carrot', 'yellow'));
$shoppingList->add(new Vegetable('tomato', 'red'));
$shoppingList->add(new Vegetable('broccoli', 'green'));

$shoppingListIterator = new ShoppingListIterator($shoppingList);

while ($shoppingListIterator->hasNextItem()) {

    $item = $shoppingListIterator->next();
    echo $item->getInfo();
}
?>

    

Outputs:


carrot yellow
tomato red
broccoli green



 

© 2018 assessmentee.com