2012-08-13 48 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