【问题标题】:Build an object comment tree构建对象注释树
【发布时间】:2012-10-20 05:37:26
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: php mysql object


    【解决方案1】:

    一般来说,我试图放下问题来理解它,看看从那里出现了哪种类型的 OO 设计。据我所见,您似乎有三个可识别的对象:要评论的对象、第一级评论和第二级评论。

    • 要评论的对象有一个第一级 cmets 列表。
    • 一级 cmets 又可以有子 cmets。
    • 二级cmets不能有孩子。

    所以你可以从建模开始:

    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 来对 cme​​ts 建模来改进它,从而删除遍历 cmets 列表和 $text 定义的重复代码。请注意,show() 消息中的注释类已经是多态的。

    【讨论】:

      猜你喜欢
      • 2010-10-12
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      • 2020-06-08
      • 1970-01-01
      相关资源
      最近更新 更多