views:

72

answers:

4

I'm writing a class to handle a memcached object. The idea was to create abstract class Cachable and all the cachable objects (such as User, Post, etc) would be subclasses of said class.

The class offers some method such as Load() which calls the abstract function LoadFromDB() if the object is not cached, functions to refresh/invalidate the cache, etc.

The main problem is in Load(); I wanted to do something similar:

protected function Load($id)
{
    $this->memcacheId = $id;
    $this->Connect();

    $cached = $this->memcache->get(get_class($this) . ':' . $id);

    if($cached === false)
    {
        $this->SetLoaded(LoadFromDB($id));
        UpdateCache();
    } else {
        $this = $cached;
        $this->SetLoaded(true);
    }
}

Unfortunately I need $this to become $cached (the cached object); is there any way to do that? Was the "every cachable object derives from the cachable class" a bad design idea?

+1  A: 

How about copying the properties from $cached to $this instead?

foreach (get_object_vars($cached) as $field => $value) {
  $this->$field = $value;
}
Matt S
A: 

You could always make it a static method (Note, for 5.3+ only, since otherwise there's no way to tell the calling class due to late static binding issues)...

protected static function Load($id) {
    $memcache = Memcache::getInstance();
    $cached = $memcache->get(get_called_class() . ':' . $id);
    if($cached === false) {
        $ret = new static();
        $ret->SetLoaded(LoadFromDB($id));
        UpdateCache();
    } else {
        $ret = $cached;
        $ret->SetLoaded(true);
    }
    return $ret;
}

Usage:

$user = User::load(4);
$user->foo;
ircmaxell
A: 

With modern ORM's mucgh of this stuff is taken care of for you: However:

http://en.wikipedia.org/wiki/Memento_pattern

Zak
+1  A: 

Is there a way to deserialize an object into “$this”?

As far as I am aware (and from reading the answers to date), the answer is no.

However it'd be fairly trivial to write a decorator object which would wrap around just about anything....

 class mydecorator {
    var $mydec_real_obj;
    function deserialize($inp)
    {
       $this->mydec_real_obj=unserialize($inp);
    }
    function __set($name, $val) 
    {
        $this->mydec_real_obj->$name=$val;
    }
    function __call($method, $args)
    {
        return call_user_func_array( 
             array(0=>$this->mydec_real_obj, 1=>$method),
             $args);
    }

 // ... etc

C.

symcbean