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:
Post a Comment