简体   繁体   中英

Symfony/Sonata get next child (Sibling)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM