2013-05-29 7 views
12

क्या आप जटिल वस्तुओं को सार्वजनिक/स्थैतिक चर/कार्यों को स्वयं परिभाषित/विरासत सहित स्टोर कर सकते हैं?दुकान जटिल वस्तुओं memcached कर सकते हैं?

मैं Memcached (http://memcached.org/)

+0

केवल अगर वे धारावाहिक रहे के बारे में बात कर रहा हूँ; और कक्षा को –

+0

को फिर से रद्द करने से पहले कक्षा को शामिल/परिभाषित किया जाना चाहिए यदि आप बंद करना चाहते हैं, तो आपको कुछ की आवश्यकता होगी जैसे https://github.com/jeremeamia/super_closure –

उत्तर

11

उपयोग 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()); 

?> 
संबंधित मुद्दे