我太累了,但我一直在和这个人摔跤。 容器可以自己具有布局,也可以在具有布局的层次结构中的某个位置具有父级。我需要找到那个布局,无论它有多远。
对象$ container有一个属性$ parent,如果不为null,则引用另一个$ container对象(相同类型)。
我认为这段代码在while条件下有问题吗?
private function findInheritedLayout($container) {
do {
if ( $container->getLayoutTemplate() ) {
return $container->getLayoutTemplate();
}
else {
if ( $container->getParent() ) {
$container = $container->getParent();
}
else {
return null;
}
}
} while ( $container->getParent() ); //flawed? looks for a parent one step too far?
}
答案 0 :(得分:1)
测试:
$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);
}
}
答案 1 :(得分:0)
你的假设是正确的。 while条件检查当前$container
是否有父项,而不检查布局。
尝试以下方法:
while (!$container->getLayoutTemplate() && $container->getParent()) {
$container = $container->getParent();
}
$template = $container->getLayoutTemplate();
return $template ?: null;