Cache_Lite とか
PEARのCache_Liteを利用して、
クラスメソッドにキャッシュ機能を付加させる方法を考えてみる。
_call メソッドを利用して、"XXX_c" というように関数の末尾に "c" がついていたら、
キャッシュ利用関数(戻り値をキャッシュにする)と見なすようにする。
[php]
<?php
require_once('Cache/Lite.php');
class Base { var $cachLifeTime = 300; function _call($name, $args) { $class = get_class($this); if (preg_match('/^(.+)c$/', $name, $m)) { $func = $m[1];
$cache = new Cache_Lite(array(
'cacheDir' => '/tmp/',
'lifeTime' => $this->cacheLifeTime,
'automaticSerialization' => TRUE,
));
$key = $class . ':' . $func . ':' . serialize($args);
$res = $cache->get($key);
if ($res !== FALSE) {
return $res;
}
$res = call_user_func_array(array($this, $func), $args);
$cache->save($res, $key);
return $res;
}
$class = get_class($this);
echo("not found function {$class}::{$name}");
}
}[/php]
これにより、
[php]
class Test extends Base {
function abc() {
return 'hello';
}
}
$test = new Test();
$test->abc; // そのまま abc() を呼び出す。
$test->abc_c; // キャッシュを利用
[/php]
Cache_Lite_Function 使ったほうが簡単なのかな。
どうなんだろ。