我想制作有限答复的评论系统。例如:
#1st comment
## reply to the 1st comment
## reply to the 1st comment
#2nd comment
#3rd comment
## reply to the 3rd comment
因此,每个评论都有一个回复树。最后,我想这样使用它,假设我在$ comment in $ dimper中有一系列来自db的对象:
foreach($comments as $comment)
{
echo $comment->text;
if($comment->childs)
{
foreach($comment->childs as $child)
{
echo $child->text;
}
}
}
所以我想我需要创建另一个对象,但不知道如何使其全部起作用。我应该使用stdclass还是其他?预先感谢。
一般而言,我试图解决问题以理解它,并查看从那里出现的类型的OO设计类型。据我所知,看起来您有三个可识别的对象:要评论的对象,第一级评论和第二级评论。
- 发表评论的对象具有第一级评论的列表。
- 第一级评论又可以带有孩子评论。
- 第二级评论不能有孩子。
因此,您可以从建模开始:
class ObjectThatCanHaveComments
{
protected $comments;
...
public function showAllComments()
{
foreach ($this->comments as $comment)
{
$comment->show();
}
}
}
class FirstLevelComment
{
protected $text;
protected $comments;
...
public function show()
{
echo $this->text;
foreach ($this->comments as $comment)
{
$comment->show();
}
}
}
class SecondLevelComment
{
protected $text;
public function show()
{
echo $this->text;
}
}
这可能是一种有效的第一种方法。如果这对您的问题有效,则可以通过创建一个复合材料来建模评论,从而删除遍历注释列表和$text
定义的重复守则。请注意,评论类在show()
消息中已经是多态性的。