duanchen7036 2017-10-05 10:53
浏览 38
已采纳

Symfony / Sonata得到下一个孩子(兄弟姐妹)

I'm looking for the cleanest way to get the next child sibling of an object (next child of the parent).

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

Let assume in this example that we are talking about pages (Sonata pages). Currently I have Page 2 (Child 2), and need the next page of the same parent (in this case child 3). In the case I have the last page (child 4), then I need the first child again.

One option would be to request the parent, then request all the childs, loop over all the childs and look for the current child. Then take the next child, or the first one in case there is no next one. But this seems like a lot of code, with a lot of ugly if logic and loops. So I'm wondering if there is some sort of pattern to solve this.

  • 写回答

1条回答 默认 最新

  • dongyan4424 2017-10-12 11:46
    关注

    Eventually I came up with the next solution:

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

    This seems like a quite clean solution to tackle this problem. We don't have an excessive amount of loops and if logic, however the code is still readable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度