Is there a way to deserialize an object in "$ this"?

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

The class offers some method, for example Load(), that calls an abstract function LoadFromDB(), if the object is not cached, the function of updating / invalidating the cache, etc.

The main problem is Load(); I wanted to do something like this:

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 $thisto become $cached(cached object); is there any way to do this? Was “every cached object comes from a cached class” a bad design idea?

+3
3

$cached $this ?

foreach (get_object_vars($cached) as $field => $value) {
  $this->$field = $value;
}
+1

"$ this"?

(, ), .

, .

 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

.

+1

You can always do this with a static method (note that only for 5.3+, since otherwise there is no way to tell the calling class due to late static binding problems) ...

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;
}

Using:

$user = User::load(4);
$user->foo;
0
source

Source: https://habr.com/ru/post/1748038/


All Articles