【问题标题】:Symfony/Sonata get next child (Sibling)Symfony/Sonata 获得下一个孩子(兄弟姐妹)
【发布时间】:2018-03-16 23:21:06
【问题描述】:

我正在寻找获取对象的下一个子兄弟(父对象的下一个子对象)的最简洁方法。

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

假设在这个例子中我们正在讨论页面(奏鸣曲页面)。目前我有第 2 页(孩子 2),并且需要同一父母的下一页(在本例中为孩子 3)。如果我有最后一页(孩子 4),那么我再次需要第一个孩子。

一种选择是请求父节点,然后请求所有子节点,遍历所有子节点并查找当前子节点。然后带下一个孩子,或者第一个孩子,以防没有下一个孩子。但这似乎是很多代码,有很多丑陋的 if 逻辑和循环。所以我想知道是否有某种模式可以解决这个问题。

【问题讨论】:

    标签: php symfony logic sonata


    【解决方案1】:

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

    /** 
    * $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};
                }
            }
        }
    

    这似乎是解决这个问题的一个非常干净的解决方案。我们没有过多的循环和 if 逻辑,但是代码仍然是可读的。

    【讨论】:

      猜你喜欢
      • 2020-05-27
      • 2018-08-10
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      相关资源
      最近更新 更多