2013-11-26 69 views
0

我太累了,但我一直在摔跤这一段时间。 一个容器可以有自己的布局,或者可以有一个父级在具有布局的层次结构的某个位置。无论线路多远,我都需要找到布局。无限期寻找父母的对象

对象$ 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

你的假设是正确的。 while条件检查当前$container是否有父级,而不检查布局。

尝试以下操作:

while (!$container->getLayoutTemplate() && $container->getParent()) { 
    $container = $container->getParent(); 
} 

$template = $container->getLayoutTemplate(); 
return $template ?: null; 
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); 
    } 
}