2013-09-30 2 views
0

결과를 캐시 할 Decorator 유형 클래스를 작성하려고합니다 (memecache로 시작). 각 메소드는 $ this-> cache-> get ($ key) 캐시를 검사해야하고, 발견되지 않으면 실제 메소드 $ this-> real-> getExpensiveInfo01 ($ param1, $ param2, $ param3)을 호출 한 다음 $ this -> 캐시 -> 집합 ($ key, $ expensiveInfo). 이제 각 메소드에는이 상용구 코드가 있습니다.PHP 5.3에서 데코레이터 패턴을 사용한 DRY

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

은 (빌어 먹을에 CentOS)를 하나의 개인 메서드 호출에 보일러 플레이트 코드를 줄이기 위해 PHP5.3에 어쨌든있다.

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

($ this-> 비싼 경우 아마도 몇 가지 검사를 추가 -> $ 이름이 호출입니다)

+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; 
} 
관련 문제