Symfony/Sonata 获得下一个 child(兄弟姐妹)
Symfony/Sonata get next child (Sibling)
我正在寻找最干净的方法来获取 object 的下一个 child 兄弟(parent 的下一个 child)。
-- Parent Object
-- Child 1
-- Child 2 (<== Current object)
-- Child 3 (<== Required object)
-- Child 4
假设在这个例子中我们正在谈论页面(奏鸣曲页面)。目前我有第 2 页 (Child 2),并且需要相同 parent 的下一页(在本例中为 child 3)。如果我有最后一页 (child 4),那么我还需要第一个 child。
一个选项是请求 parent,然后请求所有 child,遍历所有 child 并查找当前的 child。然后拿下一个child,或者第一个,以防没有下一个。但这看起来像很多代码,有很多丑陋的 if 逻辑和循环。所以我想知道是否有某种模式可以解决这个问题。
最终我想到了下一个解决方案:
/**
* $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 逻辑,但是代码仍然可读。
我正在寻找最干净的方法来获取 object 的下一个 child 兄弟(parent 的下一个 child)。
-- Parent Object
-- Child 1
-- Child 2 (<== Current object)
-- Child 3 (<== Required object)
-- Child 4
假设在这个例子中我们正在谈论页面(奏鸣曲页面)。目前我有第 2 页 (Child 2),并且需要相同 parent 的下一页(在本例中为 child 3)。如果我有最后一页 (child 4),那么我还需要第一个 child。
一个选项是请求 parent,然后请求所有 child,遍历所有 child 并查找当前的 child。然后拿下一个child,或者第一个,以防没有下一个。但这看起来像很多代码,有很多丑陋的 if 逻辑和循环。所以我想知道是否有某种模式可以解决这个问题。
最终我想到了下一个解决方案:
/**
* $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 逻辑,但是代码仍然可读。