2013-11-26 66 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); 
    } 
}