2012-08-13 25 views
-1

我有一個映射到數據庫行的用戶類。我將它緩存在memcached中,作爲使用userid作爲memcached密鑰的鍵值對。我想將所有用戶功能封裝到用戶類中,包括填充用戶類字段。在從PDO中獲取數據時,我使用PDO :: FETCH_INTO將值存儲在自我對象中。如何使用memcached執行此操作?從memcached獲取對象並在PHP中設置爲self

+0

我不明白這個問題,你卡在哪裏? – 2012-08-13 09:12:45

+0

問題是從memcached返回的對象中爲self對象分配值。 – mrd081 2012-08-14 10:49:11

回答

2

你問題的措辭和跟進的意見是有些模糊,但他們仍然指向我在以下方向:

public function __construct($id) { 
    global $pdo, $memcached; 

    $data = $memcached->get($id); 
    if($memcached->getResultCode() == Memcached::RES_SUCCESS) { 
     // this is not currently allowed in PHP 
     $this = $data; 

     // this should be your fix 
     foreach($data AS $key => $value) { 
      $this->$key = $value; 
     } 

     // or this 
     foreach($this AS $key => $value) { 
      $this->$key = $data[$key]; 
     } 

     // the difference between the fixes above is that 
     // the second is strictly limited to values defined 
     // by the class (current object) 
    } 
    else { 
     $pdos = $pdo->prepare('SELECT * FROM table_name WHERE id = ?'); 
     if($pdos) { 
      // this is not allowed in PHP 
      $pdos->execute(array(intval($id))); 
      $this = $pdos->fetch(PDO::FETCH_CLASS, get_class($this)); 

      // all of this should work fine and is allowed 
      $pdos->setFetchMode(PDO::FETCH_INTO, $this); 
      $pdos->execute(array(intval($id))); 
      $pdos->fetch(PDO::FETCH_INTO); 
     } 
    } 
} 

但不幸的是PHP不允許覆蓋的$該值在內部(它自己的內部方法調用),因此可以作爲替代方法使用靜態方法。

public static function getByID($id) { 
    global $pdo, $memcached; 

    $data = $memcached->get($id); 
    if($memcached->getResultCode() == Memcached::RES_SUCCESS) { 
     // this will work if your objects construct has a 
     // foreach similar to the ones presented above 
     $result = new self($data); 

     // or if you don't want to write a foreach in 
     // the construct you can have it here 
     foreach($data AS $key => $value) { 
      $this->$key = $value; 
     } 

     // or here 
     foreach($this AS $key => $value) { 
      $this->$key = $data[$key]; 
     } 
    } 
    else { 
     $pdos = $pdo->prepare('SELECT * FROM table_name WHERE id = ?'); 
     if($pdos) { 
      // either of these should work 
      $pdos->execute(array(intval($id))); 
      $result = $pdos->fetch(PDO::FETCH_CLASS, get_class($this)); 

      // either of these should work 
      $result = new self; 
      $pdos->setFetchMode(PDO::FETCH_INTO, $result); 
      $pdos->execute(array(intval($id))); 
      $pdos->fetch(PDO::FETCH_INTO); 
     } 
    } 

    return($result); 
} 

使用語法是MyClass::get($some_id)

+0

感謝您的回答。我們昨天剛剛實施了類似的東西:) – mrd081 2012-08-15 05:37:05

1

答案要麼是「只管去做」或者「你不這樣做」。如果你把你的信息單獨保存爲鍵/值,你不能只用一次命中就完成,你只需要手工檢索它們(使用memcached中的計算鍵創建一個新對象)。

如果你在分佈式緩存序列化的對象,你可以檢索和反序列化。

+0

問題是從memcached返回的對象中爲self對象分配值。 – mrd081 2012-08-14 10:49:56

相關問題