25 July, 2011

Caching in PHP

The term Caching refers to storing of data for later usage. Commonly used data can be cached it can be accessed faster and caching in PHP can be easier task as well, if you know what you are doing. Following code snippet demonstrates File Caching in php in which data is written to the file by caching process.

class CacheFile {
protected $fPointer;
protected $fileName;
protected $expirationTime;
protected $tempFileName;

//constructor function
//pass in the filename along with optional expiration
public function __construct($fileName, $expiration = false) {
$this->fileName = $fileName;
$this->expirationTime = $expiration;
$this->tempFileName = "$filename.".getmypid();
}

public function get() {
//check for expiration and return contents of cache file
if($this->expirationTime) {
//get the file status
$status = @stat($this->fileName);
if($status[9]) {
//check the filetime
if(($modified + $this->expirationTime) < time()) {
@unlink($this->fileName);
return false;
}
}
}
return file_get_contents($this->fileName);
}

public function put($fileBuffer) {
if(($this->fPointer == fopen($this->tempFileName, 'w')) == false) {
return false;
}
fwrite($this->fPointer, $fileBuffer);
fclose($this->fPointer);
rename($this->tempFileName, $this->fileName);
return true;
}

//remove the cache file
public function remove() {
@unlink($this->fileName);
}

//start the caching process
public function startOutputBuffer() {
if(($this->fPointer = fopen($this->tempFileName, 'w')) == false) {
return false;
}
ob_start();
}

//end the caching process
public function endOutputBuffer() {
//get the output bufer contents
$bufferContents = ob_get_contents();
ob_end_flush();
if(strlen($bufferContents)) {
fwrite($this->fPointer, $bufferContents);
fclose($this->fPointer);
rename($this->tempFileName, $this->fileName);
return true;
}
else {
fclose($this->fPointer);
@unlink($this->tempFileName);
return false;
}
}
}
?>

And the File Cache class cane be used as follows:

require_once('CacheFile.php');
$cacheData = CacheFile($pathToCacheFile);
//check if the string exists in cache
if($string = $cacheData->get()) {
var_dump($string);
}
else {
//start caching process
$cacheData->startOutputBuffer();
?>
//your page data included here
$cacheData->endOutputBuffer();
}
?>

In this way we can implement Caching in php.

No comments: