2010-12-07 6 views
2

Memcached를 사용하려면 응용 프로그램의 모든 단일 쿼리를 수정해야합니까?PDO로 Memcached를 구현하는 방법

내가 PDO 튜토리얼에서이 DB 클래스를 사용하고 있습니다 :

class DB { 

private static $host; 
private static $dbName; 
private static $user; 
private static $password; 

/*** Declare instance ***/ 
private static $instance = NULL; 

/** 
* 
* the constructor is set to private so 
* so nobody can create a new instance using new 
* 
*/ 
private function __construct() {} 

/** 
* 
* Return DB instance or create intitial connection 
* @return object (PDO) 
* @access public 
* 
*/ 
public static function getInstance() { 

    if (!self::$instance){ 
     self::$instance = new PDO("mysql:host=".self::$host.";dbname=".self::$dbName, self::$user, self::$password); 
     self::$instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    } 
    return self::$instance; 
} 

/** 
* 
* Like the constructor, we make __clone private 
* so nobody can clone the instance 
* 
*/ 
private function __clone(){} 

} /*** end of class ***/ 

는 Memcached가 통합하도록 수정의 좋은 쉬운 방법이 있습니까?

+0

가능한 복제본 [어떻게하면 PDO와 memcached를 사용하여 캐시 시스템을 설계 할 수 있습니까?] (http://stackoverflow.com/questions)/2600720/how-i-can-design-a-cache-system-using-pdo-and-memcached) – RobertPitt

+0

@ 로버트 그 질문과 그 링크를 읽었습니다. – bcmcfc

답변

3

첫째로 나는 그렇게처럼 PDO 클래스를 확장하는 구조 당신의 클래스를 다시 것 :


class DBStatement extends PDOStatement 
{ 
    public $db; 

    protected function __construct(&$db) 
    { 
     $this->db =& $db; 
    } 
    /* 
     * PDO Methods! 
    */ 

    public function rowCount() 
    { 
        return $this->foundRows; 
    } 

     public function execute($array = null) 
    { 
         if ($array === null) 
         { 
             $result = parent::execute(); 
         }else 
     { 
            $result = parent :: execute($array); 
        } 
     return $result; 
    } 
} 

class Database extends PDO 
{ 
    /** 
    * 
    * the constructor is set to private so 
    * so nobody can create a new instance using new 
    * 
    */ 
    private static $Instance; 
    public $Cache = null; 

    public function Instance() 
    { 
     if(self::$Instance === null) 
     { 
      self::$Instance = new Database; 
      self::$Instance->Cache = new Memcached; 
     } 
     return self::$Instance; 
    } 

    public function __construct() 
    { 
     parent::__construct("Connection;String"); 
     $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement', array(&$this))); 
    } 
} 
는 그 다음 방법은 실행으로, 위의 클래스 DBStatement의 예로서 오버라이드 (override) 할 것 .

결과 집합을 반환하는 각 메서드를 사용하면 해당 쿼리에 대해 고유 한 해시를 만들기 위해 쿼리를 md5 만들 것이므로 캐시에 있는지 확인한 다음 캐시에 있는지 확인하고 그렇지 않으면 그냥 반환합니다. 결과를 가져 오는 새로운 쿼리를 실행 한 다음 반환하기 전에 캐시에 저장하십시오.

+0

답변 해 주셔서 감사합니다. 별도의 rowCount 함수가 필요한 이유 또는 캐싱을 PDO 문에 제대로 통합하는 방법을 알기가 어렵습니다. PDO 문 개체는 PDO에 의해 반환되므로 캐시 항목은 문이 아닌 PDO를 확장하는 클래스에있을 필요가 없습니까? – bcmcfc

+1

PODStatement가 PDO Main에 의해 반환 되더라도, 캐시 된 버전의 데이터를 확인해야 할 때 명령문에서 execute를 실행하면 여전히 서버에 대해 실행되지 않습니다. – RobertPitt

관련 문제