Three simple php caching tehniques
No talking . Just examples
class Foo
{
private static $_bar = null;
private function getBar()
{
if ( null == self::$_bar) {
//very expensive operation
self::$bar = $this->expensiveOperation();
}
return self::$bar;
}
private function expensiveOperation()
{
return 1+1;//wow
}
}
Extending the example
class Foo
{
private function getBar()
{
if ( !this->isCached()) {
//very expensive operation
$this->saveCache($this->expensiveOperation);
}
return $this->getCache();
}
protected function saveCache($value)
{
file_put_contents($this->getCachePath(),$value);
}
protected function getCache()
{
return file_get_contents($this->getCachePath());
}
protected function isCached()
{
return is_file($this->getCachePath());
}
private function getCachePath()
{
return '/path/to/somefile.txt';
}
private function expensiveOperation()
{
return 1+1;//wow
}
}
Final example
class Cache
{
public static function isCached($tag)
{
return is_file(self::isFile(self::getCacheFile($tag)));
}
public static function save($value , $tag)
{
$file = self::getCacheFile($tag);
file_put_contents($file , $value);
}
public static function load( $tag)
{
$file = self::getCacheFile($tag);
return file_get_contents($file);
}
private static function getCachePath($tag)
{
return "/path/to/somefile_$tag.txt";
}
}
class Foo
{
public static function getBar()
{
if ( !Cache::isCached('my_tag')) {
//very expensive operation
Cache::save($this->expensiveOperation(),'my_tag');
}
return $this->load('my_tag');
}
private function expensiveOperation()
{
return 1+1;//wow
}
}
All three examples are variations of the same technique.
Of course , the file_get_contents thing is used for the example's sake only
Rss
November 10th, 2009 at 10:39 pm
I just use JG_Cache =)
November 11th, 2009 at 12:21 am
Thank you for your comment. I generally use Zend_Cache.
My post is just a simple example on how caching can be used ,on different contexts, or how it can evolve from something simple.
JG_Cache illustrates the third situation very well.
November 11th, 2009 at 2:43 am
Very useful examples. Simple, yet powerful.
November 18th, 2009 at 4:12 pm
[...] my previous post I gave some examples on how caching can evolve. However , what annoys me in the [...]