測試:
$test = new View('A');
$test->assign('A', new View('B'));
$test->assign('B', $test2 = new View('C'));
$test2->assign('D', $test3 = new View('E'));
$test3->assign('F', $searchTarget = new View('G'));
$root = RootViewIterator::findRootOf($searchTarget);
var_dump($root->getName());
結果:
string(1) "A"
迭代器:
class RootViewIterator
implements Iterator
{
protected $view;
protected $startView;
protected $key = 0;
public function __construct(View $view)
{
$this->view = $view;
$this->startView = $view;
}
public function next()
{
$this->view = $this->view->getParent();
$this->key++;
}
public function key()
{
return $this->key;
}
public function current()
{
return $this->view;
}
public function rewind()
{
$this->view = $this->startView;
$this->key = 0;
}
public function valid()
{
return null !== $this->view;
}
public static function findRootOf(View $view)
{
$result = iterator_to_array(new static($view));
end($result);
return current($result);
}
}
的觀點:
class View
{
protected $name;
protected $items;
protected $parent;
public function __construct($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function assign($key, $content)
{
if ($content instanceof View) {
$content->setParent($this);
}
$this->items[$key] = $content;
}
public function setParent(View $view)
{
$this->parent = $view;
}
public function getParent()
{
return $this->parent;
}
public function hasParent()
{
return !empty($this->parent);
}
}