Skip to content

Instantly share code, notes, and snippets.

@erikfrerejean
Created March 8, 2011 14:05
Show Gist options
  • Save erikfrerejean/860291 to your computer and use it in GitHub Desktop.
Save erikfrerejean/860291 to your computer and use it in GitHub Desktop.
<?php
class controller
{
private $container = null;
public function __construct()
{
$this->container = new container();
// Fill
for ($cnt = 1; $cnt < 6; ++$cnt)
{
$this->container->addNode("Node{$cnt}");
}
for ($cnt = 7; $cnt < 10; ++$cnt)
{
$nc = $this->container->addContainer();
for ($cnt2 = 0; $cnt2 < 3; ++$cnt2)
{
$nc->addNode("SubContainer{$cnt}::Node{$cnt2}");
if ($cnt2 == 2)
{
$nc2 = $nc->addContainer();
$nc2->addNode("SubContainer{$cnt}::SubSubContainer1::Node");
}
}
}
}
public function getIterator()
{
return new RecursiveIteratorIterator($this->container);
}
}
class container implements RecursiveIterator
{
private $data = array();
public function addNode($name)
{
$this->data[] = new node($name);
}
public function addContainer()
{
$nc = new container();
$this->data[] = $nc;
return $nc;
}
//-- Iterator implementation
private $pos = 0;
public function hasChildren()
{
print("\t::\t" . __METHOD__ . "\n");
return ($this->data[$this->pos] instanceof container) ? true : false;
}
public function getChildren()
{
print("\t::\t" . __METHOD__ . "\n");
return $this->data[$this->pos];
}
public function current()
{
print("\t::\t" . __METHOD__ . "\n");
return $this->data[$this->pos];
}
public function key()
{
print("\t::\t" . __METHOD__ . "\n");
return $this->pos;
}
public function next()
{
print("\t::\t" . __METHOD__ . "\n");
++$this->pos;
}
public function rewind()
{
print("\t::\t" . __METHOD__ . "\n");
$this->pos = 0;
}
public function valid()
{
return isset($this->data[$this->pos]);
}
}
class node
{
private $name = '';
public function __construct($name, $subNodes = false)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
$c = new controller();
$iterator = $c->getIterator();
foreach ($iterator as $i)
{
var_dump($i->getName());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment