0

我正在尝试编写一个装饰器类型类,它将结果缓存到任何东西(从 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)中是否有将样板代码减少为一个私有方法调用。

4

2 回答 2

1

不是私人的,而是公开的__call

class ExpensiveCache implements ExpensiveInterface {
    public function __call($name, $arguments) {
        $key = $name.implode('', $arguments);
        $rtn = $this->cache->get($key);
        if ($rtn === false) {
            $rtn = call_user_func_array(array($this->expensive, $name), $arguments);
            $cacheStatus = $this->cache->set($key, $rtn);
        }
        return $rtn;
    }
}

(如果 $this->expensive->$name 是可调用的,可能会添加一些检查)

于 2013-09-30T22:28:36.377 回答
0

也许是这样的:

private function getCacheKey(array $args)
{
    return implode('', $args);
}

private function getExpensiveInfo()
{
    $args = func_get_args();
    $key = $this->getCacheKey($args);
    if (($value = $this->cache->get($key)) === false) {
        $value = call_user_func_array(array($this->expensive, __FUNCTION__), $args);
        $this->cache->set($key, $value);
    }

    return $value;
}
于 2013-09-30T22:45:48.853 回答