memcached可以存储复杂的对象吗? [英] Can memcached store complex objects?

查看:157
本文介绍了memcached可以存储复杂的对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你可以存储复杂的对象,包括公共/静态变量/函数自定义/继承吗?

Can you store complex objects including public/static variables/functions self-defined/inherited?

我在说Memcached(http://memcached.org/

I am talking about Memcached ( http://memcached.org/ )

推荐答案

使用 http://php.net/manual/en/function.serialize.php p>

use http://php.net/manual/en/function.serialize.php

<?php

// connect memcache
$memcache_obj = new Memcache;
$memcache_obj->connect('localhost', 11211);

// simple example class
class MyClass {
    private $var = 'default';

    public function __construct($var = null) {
        if ($var) {
            $this->setVar($var);
        }
    }

    public function getVar() {
        return $this->var;
    }

    public function setVar($var) {
        $this->var = $var;
    }
}

$obj1 = new MyClass();
$obj2 = new MyClass('test2');
$obj3 = new MyClass();
$obj3->setVar('test3');

// dump the values using the method getVar
var_dump($obj1->getVar(), $obj2->getVar(), $obj3->getVar());

// store objects serialized in memcache, set MEMCACHE_COMPRESSED as flag so it takes less space in memory
$memcache_obj->set('key1', serialize($obj1), MEMCACHE_COMPRESSED);
$memcache_obj->set('key2', serialize($obj2), MEMCACHE_COMPRESSED);
$memcache_obj->set('key3', serialize($obj3), MEMCACHE_COMPRESSED);

// unset the objects to prove it ;-)
unset($obj1, $obj2, $obj3);

// get the objects from memcache and unserialze
// IMPORTANT: THE CLASS NEEEDS TO EXISTS! 
// So if you have MyClass in some other file and include it, it has to be included at this point
// If you have an autoloader then it will work easily ofcourse :-)
$obj1 = unserialize($memcache_obj->get('key1'));
$obj2 = unserialize($memcache_obj->get('key2'));
$obj3 = unserialize($memcache_obj->get('key3'));

// dump the values using the method getVar
var_dump($obj1->getVar(), $obj2->getVar(), $obj3->getVar());

?>

这篇关于memcached可以存储复杂的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆