I'm trying to get my head around SPL iterators and I've come up with 2 ways to handle it. I see the first version to be less complicated but the second version has composition feel to it (I think).
What am I not seeing is which one is preferable over the other? Or am I just over complicating this?
Here are my thoughts:
The object implements an iterator:
class BoxOfChocolates implements Iterator {
private $id
private $name; // e.g. Valentine's Heart Box
private $maker; // e.g. Hersheys
private $items; // array
public function getChocolates() {
$query = ...
foreach($rows as $row) {
$this->_items[] = new Chocolate() ...
}
}
// ... necessary iterator implementation stuff
}
The object contains an iterate-able object:
class BoxOfChocolates {
private $id;
private $name;
private $maker;
private $items; // chocolates object
public function getChocolates() {
$this->items = new Chocolates();
$this->items->getChocolates();
}
}
class Chocolates implements Iterator {
private $items;
public function getChocolates() {
$query = ...
foreach($rows as $row) {
$this->_items[] = new Chocolate() ...
}
}
// ... necessary iterator implementation stuff
}