Loading...
PHP Fragment cache solution Sometimes we want to cache a part php script rather caching the whole page.

For example above right side list is updating after 1 hour, so why not cache it for 1 hour rather shooting database for each request.
My illustration will cache a time stamp (so when can verify when it was updated lastly):
// init. Fragment cache generator class
// pass a cache unique key
$c = new Cache( “abc” );
while( $c->startCache() ) {
// all logic should be inside while loop
// rather placing else where.
echo time();
// it needs to be invoked because we want to finish
// our caching task right here,
$c->endCache();
}
//print out your content from cache or fresh (first time) echo “CONT: “.
$c->getContent();
?>
Now have a look on “Cache” class how does it work….
class Cache {
private $id;
private $createdOn;
private $content;
private $notCached;
// we need to know when the cache has been lastly created
public function __construct( $id ) {
$this->id = $id;
$this->createdOn = time();
}
// let cache now fragment started
public function startCache() {
// be sure if already cache exists on the same ID
// load it or create new cache
if( !$this->_hasCache()) {
$this->notCached = true;
ob_start();
}
else {
$this->notCached = false;
}
return $this->notCached;
}
// for illustration I have used flat file caching, though it can be replaced by
// MemCached solution or other shared memory solution.
private function _hasCache() {
$hasCache = file_exists( $this->id.”.cache” );
if( $hasCache ) {
$fp = fopen( $this->id.”.cache”, “r” );
$this->content = fread( $fp, filesize( $this->id.”.cache” ) );
fclose( $fp );
}
return $hasCache;
}
// let cache know fragment is over and finish
public function endCache() {
$this->content = ob_get_contents();
ob_end_clean();
// create cache file
$fp = fopen( $this->id.”.cache”,”w” );
fputs( $fp, $this->content );
fclose( $fp );
}
// let’s get your cache content
public function getContent( ) {
return $this->content;
}
}
?>
Though very straight forward solution, it can be optimized using Shared Memory or MemCached solution.
NOTE: this implementation is just for illustration purpose. it should contain expire system, event management etc.. important stuffs. to make this class really helpful.
– nhm tanveer hossain khan (hasan)







| www.flickr.com |
Leave a reply