Speeding up page rendering with PHP Cache Lite

From FundaWiki

Jump to: navigation, search

Cache_Lite is a PEAR module for PHP that can be used to speed up page rendering where php is the slowing part. This guide shows you how you can use it together with Fundanemt.

Installation

You can either install if from the source (link given above) or from one of the binary packages. On Linux that could look like:

Mandriva Linux: urpmi php-pear-Cache_lite

Debian: apt-get install php-cache-lite

etc.

Setup

You can easily use Cache_Lite with an existing fundanemt site by simply adding some extra lines of code in your index.php (the renamed fundanemt.php). The lines are the following: In the top you add:

require_once('Cache/Lite.php');

And on the lines just after you instantiate the parser object (but before you print the DOCTYPE line) you add the following:

$options = array(
    'cacheDir' => '/tmp/',  #remember trailing /
    'lifeTime' => 3600,
    'pearErrorMode' => CACHE_LITE_ERROR_DIE
);
// Create a Cache_Lite object
$Cache_Lite = new Cache_Lite($options);

//hack to get news to work correctly (is needed due to use of GET variables)
if ($_GET["nummer"]){
   $group = "news";
   $id=$_GET["nummer"];
}else{
   $group="main";
   $id =$parser->ID;
}

if ($data = $Cache_Lite->get($id,$group)) {
    echo $data; // print site copy from cache
}else{
ob_start();  // start output buffering 

Notice that the }else{ isn't closed. This will be done after all the lines that creates the actual page content.

Below all the lines that makes the page you add the following

//fill cache object
  $data = ob_get_contents(); //get all the lines from the output buffer
  ob_end_clean();            //empty the output bufer 
  $Cache_Lite->save($data,$id, $group); //Save a static copy of the page to the cache 
  print $data;                 //output the actual page content
} //cache else end

If everything goes well, the cache will now start to fill up when the page is visited and you should be able to see a reduction in loadtime, database connection and memory+processor usage.</nowiki></pre>

- Kim Schulz DevTeam Danmark

Personal tools