-1

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

4

2 回答 2

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 不允许在内部(在它自己的方法调用中)覆盖 $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).

于 2012-08-14T12:25:16.997 回答
1

答案是“只做”或“你不做”。

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

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

于 2012-08-13T09:39:03.007 回答