从 memcached 获取对象并在 PHP 中设置为 self


Getting object from memcached and setting to self in PHP

我有一个映射到数据库行的用户类。我将其缓存在 memcached 中作为键值对,用户 id 作为 memcached 键。我想将所有用户功能封装到用户类中,包括填充用户类字段。从 PDO 获取时,我使用 PDO::FETCH_INTO 将值存储在 self 对象中。如何使用内存缓存来做到这一点?

您的问题的措辞和后续评论有些模棱两可,但它们仍然为我指明了以下方向:

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 不允许在内部(在其自己的方法调用中)覆盖 $this 的值,因此作为替代方案可以做的是使用静态方法。

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)

答案要么是"只是做",要么是"你不做"。

如果您将信息单独保存为键/值,则不能只通过一次点击来完成,只需手动检索它们(创建一个新对象,用 memcached 中的计算键填充自身)。

如果你有一个对象在memcached中序列化,你可以检索它并反序列化。