我正在尝试编写一个装饰器类型类,它将结果缓存到任何东西(从 memecache 开始)。每个方法都需要检查缓存 $this->cache->get($key) 如果没有找到调用真正的方法 $this->real->getExpensiveInfo01($param1, $param2, $param3) 然后设置它 $this ->缓存->设置($key,$expensiveInfo)。所以现在每个方法都有这个样板代码;
class ExpensiveCache implements ExpensiveInterface
{
public function getExpensiveInfo01($param1, $param2, $param3)
{
$key = __FUNCTION__ . $param1 . $param2 . $param3;
$rtn = $this->cache->get($key);
if ($rtn === false) {
$rtn = $this->expensive->getExpensiveInfo01($param1, $param2, $param3);
$cacheStatus = $this->cache->set($key, $rtn);
}
return $rtn;
}
public function getExpensiveInfo02($param1, $param2)
{
$key = __FUNCTION__ . $param1 . $param2;
$rtn = $this->cache->get($key);
if ($rtn === false) {
$rtn = $this->expensive->getExpensiveInfo02($param1, $param2);
$cacheStatus = $this->cache->set($key, $rtn);
}
return $rtn;
}
public function getExpensiveInfo03($param1, $param2)
{
$key = __FUNCTION__ . $param1 . $param2;
$rtn = $this->cache->get($key);
if ($rtn === false) {
$rtn = $this->expensive->getExpensiveInfo03($param1, $param2);
$cacheStatus = $this->cache->set($key, $rtn);
}
return $rtn;
}
}
PHP5.3(该死的CentOS)中是否有将样板代码减少为一个私有方法调用。