mobby_6kl has asked for the wisdom of the Perl Monks concerning the following question:
I finally decided to implement a "comments" section/feature for my (future) web site, and the basic flat layout (like on fark.com) was ready in a matter of hours. The next step was implementing the threaded model, like on pm or slashdot.
My comments table in the DB (Postgre) has a comment id (cid) and parent id (pid) columns. This simple method provides enough information to figure out the relationship, but I ran into problems when trying to output the comments.
My first idea was, for each comment, to query the DB for comments where their pid == this comment's cid. Add that comment, repeat. When there were no more such comments, drop to the previous level, and continue. Besides not being able to make this work properly, this approach doesn't look right to me, especially from the DB queries point of view.
After a while I came to the conclusion that I'll need to build a tree and then add the comments when traversing it. After some more time with the pm DAG_Node tutorial and experimenting with references, I managed to get this test script to work:
my $comm_tree = Tree::DAG_Node->new; #create the root node $comm_tree->name('CommentRoot'); my %noderef; #hash of node references, with PID as keys $noderef{0} = \$comm_tree; #replies to the story have PID==0
while ( my $hashref = $query->fetchrow_hashref() ) { my $tmpref = $noderef{ $$hashref{pid} }; #reference to the parent node my $cid = $$hashref{cid}; #CID will be used several times my $nodeone = Tree::DAG_Node->new( { name => $cid, #CID as node name mother => $$tmpref, #mother is the parent } ); $noderef{ $cid } = \$nodeone; #add this node ref to the hash $comm_hashref{ $cid } = $hashref; }
$comm_tree->walk_down( { callback => sub { my $node = shift; my $tmp = $comm_hashref{ $node->name }; $$tmp{level} = $_[0]->{_depth}; #add a level key for ht +ml indentation push @comm_loop, $tmp unless ($node->name eq 'CommentRoot' +); #for the HTML::Template loop }, _depth => 0, treename => 'CommentRoot' } ); $template->param(comment_loop => \@comm_loop);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Implementing threaded/nested forum
by Fletch (Bishop) on Aug 15, 2006 at 14:38 UTC |