Effective comments caching techniques

I am looking for an effective way of caching article comments on my page. Since using pagination can’t get it done. Should I cache comment list fragment on every page with an article? Or should I cache all comments directly from db and then get pages from cache.

Any fresh ideas would be a blessing.

Thanks in advance.

Personally, I don’t like caching rendered html for several reason. So I suggest to cache the actual models for each comments page. You can do that with a CDbCacheDependency.

Some code to illustrate:





$cacheKey = "articleComments.{$article->id}.{$page}";


if (false === ($comments = Yii::app()->cache->get($cacheKey)))

{


   // get the comments for the current page

   // $comments = ...


   $cacheDependency = new CDbCacheDependecy("

      SELECT COUNT(*) FROM `article_comment`

         WHERE `article_id` = {$article->id}

   ");


   Yii::app()->cache->set($cacheKey, $comments, 0, $cacheDependency);


}



So the the comments will stay in cache until the amount of comments for the article changes. This is not perfect solution though. You may create special column "last_comment_timestamp" in article table. Then use CDbCacheDependency this way:




$cacheDependency = new CDbCacheDependecy("

   SELECT `last_comment_timestamp` FROM `article`

      WHERE `id` = {$article->id} LIMIT 1

");



Thank you very much :)

Is this method good enough? You based the caching on the "page" parameter. It would be good if there would be a fixed number of comments. What if I change the setting how many posts should be per page.

I think all comments should be cached and then create my own pager that will gather comments from it.

Am I correct ?

You can additionaly append the number of pages to display to the cache key. So the cache isn’t valid anymore when you change that variable. Your proposed method would require additional work. Why not keep it simple?