构建对象注释树

I want to make comment system with limited replies. For instance:

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

So there is one reply tree for the each comment. And in the end I'd like to use it like that, assuming I have in $comments array of objects from db:

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

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

So I guess I need to create another object but don't know how to make it all work. Should I use stdClass or something else? Thanks in advance.

In general terms I try to lay down the problem to understand it and see what type of OO design rises from there. As far as I can see it looks like you have three identifiable objects: the object to comment on, the first level comment and the second level ones.

  • The object to comment on has a list of first level comments.
  • First level comments can in turn have child comments.
  • Second level comments can't have childs.

So you can start by modeling that:

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;
     }
}

That could be a valid first approach. If this works for your problem you could improve it by creating a composite to model the comments, and thus remove the duplicated code of traversing the list of comments and the $text definition. Note that the comment classes are already polymorphic in the show() message.