2013-09-30 53 views
0

我想寫一個裝飾器類型的類,將緩存結果無論(從memecache開始)。每個方法需要檢查緩存$ this-> cache-> get($ key),如果沒有找到,調用真實方法$ this-> real-> getExpensiveInfo01($ param1,$ param2,$ param3),然後將其設置爲$ this - > cache-> set($ key,$ expensiveInfo)。所以現在每種方法都有這樣的樣板代碼;DRY與裝飾模式在PHP 5.3

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),以減少鍋爐板代碼到一個私人方法調用。

+0

請不要討厭CentOS,它是一隻性感的狐狸。 – Mark

回答

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; 
    } 
} 

(也許添加一些檢查$這個 - >昂貴 - > $ name是可調用)

+0

忘了所有關於__call的致謝。我仍然不得不使用實現的接口方法來包裝這個調用,但這種方式更合理。 – Clutch

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; 
}