As your site is growing you need focus more and more on site performance. If your content is not changing in every minutes but you have a lot of visitors then your webserver is making a lot of unnecessary work. The server processes your PHP scripts always, however the output is the same. Using cache mechanism we will process the script once but use it more times.
How it works
The cache mechanism is not so complicated. The main idea is that we store the processed output in a file and in case of a new request we check if the file exists or not. If it exists and not to old then we just send the file content to the client. If the file doesn't exists or to old then we process the PHP script. We can save a lot of time in case of scripts with intensive database usage.
Implementation
We will create a separate new Cache class which has 3 important functions:
starteCache()
endCache()
cleanCache()
The class skeleton
Before we begin to implement the functions we need to create the skeleton of the class with the class variables. We need to define class variables to control cache behaviour. See the comments in the code below:
Besides the class variables we define an internally used function to measure the time we spent with processing. This is the getMicroTime() function and looks like this:
The startCache() function
Now we can start with the most important function of our class. The use case of the startCache() function is the following:
Save actual time
Check file existence and age.
If file exists and not to old then display its content and exit.
If file doesn't exists then set a caching flag to true.
The code is the following:
The endCache() function
If the actual page was not cached yet and the caching flag is set to true then this function will save the output buffer to a file and of course displays it as well. At the end just for information it displays the total processing time as well. The source looks like this:
The cleanCache()
This is the last function and it is quite simple. This function only checks the cache directory and removes all of the files in it.
Usage of the class
If you want to cache your pages you need to extend your code a bit with the new cache class. It only takes some line of code. First we need to import the cache class and create a cache object afterwards. As we have the object we can call the startCache() function. At the end of the file we need to insert the endCache() function and we are ready.
An example code looks like this:
How it works
The cache mechanism is not so complicated. The main idea is that we store the processed output in a file and in case of a new request we check if the file exists or not. If it exists and not to old then we just send the file content to the client. If the file doesn't exists or to old then we process the PHP script. We can save a lot of time in case of scripts with intensive database usage.
Implementation
We will create a separate new Cache class which has 3 important functions:
starteCache()
endCache()
cleanCache()
The class skeleton
Before we begin to implement the functions we need to create the skeleton of the class with the class variables. We need to define class variables to control cache behaviour. See the comments in the code below:
Code:
<?php class Cache { var $status = true; // True to switch on cache and false to switch it off var $cacheDir = 'cache/'; // The default directory where to store chached files var $cacheFile = ''; // The content of the actual cached file var $timeOut = 1000; // The time how long the cached file remains reusable var $startTime = 0; // The startime to determine script execution time var $cache = true; // Shows if chaching actual content is needed } ?>
Code:
<?php function getMicroTime() { list($usec, $sec) = explode(" ",microtime()); return ((float)$usec + (float)$sec); } ?>
Now we can start with the most important function of our class. The use case of the startCache() function is the following:
Save actual time
Check file existence and age.
If file exists and not to old then display its content and exit.
If file doesn't exists then set a caching flag to true.
The code is the following:
Code:
<?php function startCache(){ $this->startTime = $this->getMicroTime(); if ($this->status){ $this->cacheFile = $this->cacheDir.urlencode( $_SERVER['REQUEST_URI'] ); if ( (file_exists($this->cacheFile)) && ((fileatime($this->cacheFile) + $this->timeOut) > time()) ) { //Read file from the cache $handle = fopen($this->cacheFile , "r"); $html = fread($handle,filesize($this->cacheFile)); fclose($handle); // Display the content echo $html; //Display the rendering time echo '<p>Total time: ' .round(($this->getMicroTime())-($this->startTime),4).'</p>'; //Exit from the code as we displayed cached data exit(); } else { // Set to save generated content into file $this->caching = true; } } } ?>
If the actual page was not cached yet and the caching flag is set to true then this function will save the output buffer to a file and of course displays it as well. At the end just for information it displays the total processing time as well. The source looks like this:
Code:
<?php function endCache(){ if ($this->status){ if ( $this->caching ) { //You were caching the contents so display them, and write the cache file $html = ob_get_clean(); echo $html; $handle = fopen($this->cacheFile, 'w' ); fwrite ($handle, $html ); fclose ($handle); //Display the rendering time echo '<p>Total time: '.round(($this->getMicroTime()-$this->startTime),4).'</p>'; } } } ?>
This is the last function and it is quite simple. This function only checks the cache directory and removes all of the files in it.
Code:
<?php function cleanCache(){ if ($handle = opendir($this->cacheDir)) { while (false !== ($file = readdir($handle))) { if (is_file($this->cacheDir.$file)) unlink($this->cacheDir.$file); } closedir($handle); } } ?>
If you want to cache your pages you need to extend your code a bit with the new cache class. It only takes some line of code. First we need to import the cache class and create a cache object afterwards. As we have the object we can call the startCache() function. At the end of the file we need to insert the endCache() function and we are ready.
An example code looks like this:
Code:
<?php require_once('cache.class.php'); $CacheManager = new Cache(); $CacheManager->startCache(); echo "Start Cache example at: ".date('H:i:s')."<br/>"; sleep(2); echo "End Cache example at: ".date('H:i:s')."<br/>"; echo "<br/><a href='clear.php'>Clean the cache</a><br/>"; $CacheManager->endCache(); ?>