Skip to main content

Advanced Caching Technique - Block Randomization

Introduction

I'm currenlty working on a site where I want to improve performance of dynamic pages. One of the greatest techniques to do is to cache dynamic content and serve the generated output (HTML).

It's not as easy as we all want it to be when you have all sorts of weird blocks on the page: User login area, random content, ..etc

As I had a very pleasent experience with eZ components last week, I decided to take a look at the components, but then i remembered it works on PHP5. This project is on PHP4, I had to look for an alternative and decided to use PEAR::Cache_Lite.



Example

Blocks
In the figure above we can see that we have 4 content blocks coming from tha database, let's assume this is our homepage. And let's also assume that we are trying to get random content, e.g. 3 random blogs, 3 random posts ..etc

An example would look something like this before caching

[coolcode lang="php"]

$query = "SELECT title, username FROM blogs ORDER BY RAND() LIMIT 3";
$result=mysql_query($query);

while( $row = mysql_fetch_assoc($result) ){

echo $row['title'];

}

[/coolcode]

Caching: Take 1

We can easily cache this block using Cache_Lite output caching as follows:

[coolcode lang="php"]

require_once 'Cache/Lite/Output.php';

$options = array(
'cacheDir' => '/tmp/site_cache/',
'lifeTime' => 1000,
);

$cache = new Cache_Lite_Output($options);
if (!($cache->start('blogs_block' ))) {
// Cache missed... start caching this block

$query = "SELECT title, username FROM blogs ORDER BY RAND() LIMIT 3";
$result=mysql_query($query);

while( $row = mysql_fetch_assoc($result) ){

echo $row['title'];

}

}

[/coolcode]

Well, there's a clear problem, after the first hit, the block will be cached, and anyone who vists the page during the lifetime of the cache will keep seeing the same block! This abuses the whole concept of serving random content. We need to figure out a solution...

Caching: Take 2

I came up with a very simple solution! I will make the content appear as random, but infact it is cached, just modify the line that starts the cache as follows:

[coolcode lang="php"]

if (!($cache->start('blogs_block' . rand(1,10) ))) {
[/coolcode]

What this does is allow for caching of 10 blocks, this will do the trick, give the users 10 cached blocks. If we have 4 different content blocks and allow 10 random blocks each, we end up by having 10x10x10x10 =10000 different page combinations.

Caching: Take 3

While the solution above meets my needs, I need something a bit cleaner than having rand() everytime. The first solution I came up with was to write the following class that extends Cache_lite and allows for cache randomization. Download the Class.

Using the cache randomizer is very simple, here's an example.

[coolcode lang="php"]

require_once 'Cache/Lite/Output/Random.php';

$options = array(
..........
);

$cache = new Cache_Lite_Output_Random($options);

//Set the number of random blocks to be cached
$cache->setRand( 10 );

if (!($cache->start('blogs_block' ))) {
// Cache missed... start caching this block

$query = "SELECT title, username FROM blogs ORDER BY RAND() LIMIT 3";
$result=mysql_query($query);

while( $row = mysql_fetch_assoc($result) ){

echo $row['title'];
}

}

//to disable caching and go back to normal behaviour to keep using the same object
$cache->clearRand();

//to change the number of random blocks for another block
$cache->setRand( 20 );
[/coolcode]

Conclusion

Random block caching is very useful when you want to acheive high performance, yet allow random content from a datasource (Database). If we had a page with 4 blocks, and allow 10 random blocks, we get (Theoritically) 10000 page combinations. Although we only have 40 cache blocks stored on the server.

[tags] pleasent experience, random posts, output html, output options, simple solution, dynamic content, php4, pear, all sorts, lifetime, array, blogs [/tags]

Comments

  1. Syntux Blog: Advanced Caching Technique - Block Randomization...

    ...

    ReplyDelete
  2. The Smarty template engine is able to handle dynamic blocks within static pages very well. I would recommend having a look at it.

    ReplyDelete
  3. Advanced Caching Technique - Block Randomization...

    [...]Advanced Caching Technique with PHP PEAr[...]...

    ReplyDelete
  4. I'm looking for suggestions on how to cache blocks of queries in WordPress. Caching the whole page is easy. I only need to instantiate the Cache object on index.php and the job is done. But, caching blocks are more confusing for me to apply.

    ReplyDelete
  5. That's a very simple solution to a potentially hard issue. Good read!

    Another solution may be to set a lower cache lifetime for this particular block and go from there - there would then be no need to create 10 different cache files, only needing a single one. The latter would be particularly useful for high traffic sites.

    ReplyDelete
  6. Replica Louis vuitton handbag...

    [...]Advanced Caching Technique – Block Randomization - Don't Say Geek! Say Syntux! - Your freedom is worth more than you think. Take advantage of it while you can.[...]...

    ReplyDelete

Post a Comment

Popular posts from this blog

اهم التطورات العلمية في العام ٢٠١٩

?????? ?????

?????, ?????, ????? ??? ???? ?????! ?? ????? ??????? ???, ??? ?? ???? ?? ?????? ??? ???? ?? ???? ??? ???? ?? ??? ???? ???? , ???? ???? ????? ???????, ????????, ???? ???????, ???? ? ???? ? ???? ????? ???? ????? ??????, ?????? ???? ?? ????? ?????? ???? ????? ??? ??????? ?? ????? ? ??? ?? ??????? ???????? ?? ???? ?? ????? ???? ????? ??? ?????? ? ???? ?????? ????? ? ???? ????? ?????? ???? ?????? ???? ???? ????? ? ???????? ???? ???????, ??? ?????? ????? ?? ??? ????? ?????? ??? ??????? ??? ??? ??????? ????? ???? ? ???? ????? ??? ???? ??? ???? ???? ??????, ?? ????? ??? ?????? ???????? ??? ?????? ?? ??? ???? ???? ?? ??, ???? ???? ??? ?? ????? ?????? ??????

القضاء: لا دليل على أن مقتحمي الكونغرس خططوا لقتل مشرعين

أكد محققو وزارة العدل الأمريكية أنهم لم يجدوا حتى الآن أي دليل على أن أنصار دونالد ترامب الذين هاجموا مبنى الكونغرس الأسبوع الماضي خططوا لاحتجاز مسؤولين منتخبين وقتلهم. يأتي ذلك في الوقت الذي أُوقفت فيه الشرطة، الجمعة، رجلا مسلّحا في واشنطن خلال محاولته عبور إحدى نقاط التفتيش في محيط مبنى الكونغرس حيث ستقام الأربعاء مراسم تنصيب جو بايدن. في ذات الوقت أفادت شبكة NBC الأمريكية، بأن مكتب التحقيقات الفيدرالي يحقق في إمكانية تمويل حكومات أو جماعات اقتحام مبنى الكونغرس. وقالت مصادر للشبكة: "المكتب يحقق في مدفوعات "بيتكوين" بقيمة 500 ألف دولار، يبدو أنه تم تحويلها من قبل مواطن فرنسي، لشخصيات ومجموعات رئيسية يمينية قبل اندلاع أعمال الشغب". وفي جلسة استماع في محكمة أريزونا بشأن اعتقال أحد مثيري الشغب جاكوب تشانسلي الذي يؤمن بنظرية المؤامرة ومن أتباع الحركة اليمينية المتطرفة "كيو-آنون"، تراجع المدعون الفيدراليون عن اتهامات سابقة بأن أنصار ترامب كانوا يخططون "لاحتجاز مسؤولين منتخبين وقتلهم" في هجوم السادس من كانون الثاني/ يناير في واشنطن. ع