2017-10-05 59 views
1

我正在寻找最干净的方式来获得对象(父母的下一个孩子)的下一个孩子的兄弟姐妹。Symfony/Sonata得到下一个孩子(兄弟姐妹)

-- Parent Object 
     -- Child 1 
     -- Child 2 (<== Current object) 
     -- Child 3 (<== Required object) 
     -- Child 4 

假设在这个例子中我们正在讨论页面(索纳塔页面)。目前我有第2页(儿童2),需要同一父母的下一页(在本例中为子女3)。如果我有最后一页(孩子4),那么我需要第一个孩子。

一种选择是请求父母,然后请求所有孩子,循环所有孩子并寻找当前孩子。然后带下一个孩子,或者第一个孩子,以防下一个孩子。但是,这看起来像很多代码,如果逻辑和循环有很多丑陋的。所以我想知道是否有某种模式来解决这个问题。

回答

0

最后我想出了一个解决方案:

/** 
* $siblings is an array containing all pages with the same parent. 
* So it also includes the current page. 
* First check if there are siblings: Check if the parent has more then 1 child 
**/ 
if (count($siblings) != 1) { 
     // Find the current page in the array 
     for ($i = 0; $i < count($siblings); $i++) { 

      // If we're not at the end of the array: Return next sibling 
      if ($siblings{$i}->getId() === $page->getId() && $i+1 != count($siblings)) { 
       return $siblings{$i+1}; 
      } 

      // If we're at the end: Return first sibling 
      if ($siblings{$i}->getId() === $page->getId() && $i+1 == count($siblings)) { 
       return $siblings{0}; 
      } 
     } 
    } 

这似乎是一个很干净的解决方案来解决这个问题。我们没有太多的循环,如果逻辑,但代码仍然可读。