Commentator array

Last modified: January 5, 2008 - 20:45

Lately on my website, which runs Drupal 4.7.4, I have been getting serious performance problems. In one hand I have a lot of modules installed. In the other hand I have a lot of personal code I have wrote to make my site more attractive.

One of these things was to show user's profile data on every comment, just below user’s image. Data like location, country and a nice country flag.

Well, the only way I could imagine to do this was either loading user's profile or querying DB on comment.tpl.php. That means I had to repeat this operations on every comment. Of course this was totally redundant if the same user was commenting more than once in the same thread, having nodes were I was loading some user's profiles even more than 20 times. This of course is a bad practice and makes your site pretty slow.

So today I was thinking it would be cool to load all commentators information before displaying the comments. And here is how I made it.

1. On node.tpl.php file, after node has been closed, add this php code:

    if ($node->comment) {
    global $commentators;
    $commentators = mystuff_getcommentators($node->nid);
    }

2. On template.php file, create this function:

function mystuff_getcommentators($nid) {
  $result = db_query("select distinct uid from {comments} where uid > 0 and nid = $nid");
  while ($u = db_fetch_object($result)) {
  profile_load_profile($u);
  $commentators[$u->uid] = $u;
  }
  return $commentators;
}

Of course, on this function you can add other stuff to the user object besides user's profile.

3. On comment.tpl.php file, display user's info whenever you want it:

      global $commentators;

      if ($picture) { print theme('user_picture', $comment, 'comment'); }

      if ($comment->uid) {
        print $commentators[$comment->uid]->profile_location_city . "<br/>";
        print $commentators[$comment->uid]->profile_location_state . "<br/>";
        print $commentators[$comment->uid]->profile_location_country . "<br/>";
     }

(Profile fields must be set on profile settings page)

And that's it! I love to do stuff without touching a line of Drupal's or modules code.

PS: I have been looking for some kind of solution for this on the forum, but haven't found anything so I did it myself.

PS2: Should this be on PHP snippets section?

 
 

Drupal is a registered trademark of Dries Buytaert.