我想寫一個裝飾器類型的類,將緩存結果無論(從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),以減少鍋爐板代碼到一個私人方法調用。
請不要討厭CentOS,它是一隻性感的狐狸。 – Mark