构建对象注释树

时间:2012-10-30 19:40:44

标签: php mysql object

我想用有限的回复制作评论系统。 例如:

#1st comment
## reply to the 1st comment
## reply to the 1st comment
#2nd comment
#3rd comment
## reply to the 3rd comment

因此每条评论都有一个回复树。 最后我想像这样使用它,假设我在$ comments中有来自db的对象数组:

foreach($comments as $comment)
{
    echo $comment->text;

    if($comment->childs)
    {
        foreach($comment->childs as $child)
        {
            echo $child->text;
        }
    }
}

所以我想我需要创建另一个对象,但不知道如何使它全部工作。我应该使用stdClass还是其他什么? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

总的来说,我试图解决问题以理解它,并从那里看到什么类型的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;
     }
}

这可能是一种有效的第一种方法。如果这适用于您的问题,您可以通过创建composite来建模注释来改进它,从而删除遍历注释列表和$text定义的重复代码。请注意,注释类在show()消息中已经是多态的。