Implementing Caching in Core PHP

PHP Caching is used to Speed up Dynamically Generated Sites

Instead of regenerating the page every time, the scripts running this site generate it the first time they’re asked to, then store a copy of what they send back to your browser. The next time a visitor requests the same page, the script will know it’d already generated one recently, and simply send that to the browser without all the hassle of re-running database queries or searches.

Below is the overview of how cache works:

php-cache-system

 

To achieve caching we can use many such as Memcache, Simple File that store entire page as cache etc.

We will be using the example of Cache Master. It is a user defined class with some functions to store and retrieve cache files.

For storing data in cache file we need to set:
1. Cache Directory
2. Expire Interval in seconds

Below is the code to how to use the same:

<pre>

<?php

$someData = new stdClass();
$someData->oneItem = ‘One Item’;
$someData->twoItem = ‘Two Item’;
$someData->threeItem = ‘Three Item’;

$jsonEncodedData = json_encode($someData);
$key = ‘SomeUniqueId’;
$customDirectory = ‘/tmp/customDirectory/’;

/*
* Cache it
*/
$CachedMaster = new CacheMaster(); // user defined class
$CachedMaster->setCacheDir($customDirectory);
$CachedMaster->put($key, $jsonEncodedData);

/*
* Load it
*/
if( $CacheMaster->exists($key) )
{
$x = json_decode( $CacheMaster->get($key), true);
echo ‘<pre>’;
print_r($x);
echo ‘</pre>’;
}

?>

</pre>

Download Cache Master file from here.

Advertisements