[NEED FOLLOWUP, HAS NOT SOLVED] Help me to implement cache for my lookup table

Here's my problem. I have a bunch of myisam lookup tables containing id and name, and Models in my project depend on the lookup tables to display name. Thanks to the belongsTo method, I can easly get the table by accessing $model->Aliasname->name;. But if it used to often it will continually fetch from database. Please help me to implement the method to cached the name. Here is my uncached helper method to retrieve the name

class ModelBase implements \Phalcon\Mvc\Model{
    public function nameOf($model){
        //TODO: implement a cache here
        $x = $this->getRelated($model);
        $name =  $x ? $x->name : null;
        return $name;
    }
}


85.4k

You can use APC or other in-memory cache:

class ModelBase implements \Phalcon\Mvc\Model
{
    public function nameOf($model)
    {
        //TODO: implement a cache here
        $key = get_class($this) . '-' . $model;
        $x = apc_fetch($key);
        if ($x !== null) {
            $x = $this->getRelated($model);         
            $name =  $x ? $x->name : null;
            apc_store($key, $x);
            return $name;
        }
    }
}

Using Phalcon\Cache:


class ModelBase implements \Phalcon\Mvc\Model
{
    public function nameOf($model)
    {       
        $key = get_class($this) . '-' . $model;

        $cache = $this->getDI()->getCache();

        $x = $cache->get($key);
        if ($x !== null) {
            $x = $this->getRelated($model);         
            $name =  $x ? $x->name : null;
            $cache->save($key, $x);
            return $name;
        }
    }
}

@Phalcon: It won't work. since the cache will need not only the classname info, but also the the property value of the class which is used to store the foreign key. The problem is, how could the nameOf method in the ModelBase class figure out which property used for its respective foreign key?


class ModelBase implements \Phalcon\Mvc\Model
{
  public function nameOf($model)
  {    
    $foreignKey = FigureOutWhichPropertyIsTheForeignKeyOfModel($model);
    $key = get_class($this) . '-' . $model .'-'. $this->{$foreignKey};

    $cache = $this->getDI()->getCache();

    $x = $cache->get($key);
    if ($x !== null) {
      $x = $this->getRelated($model);      
      $name =  $x ? $x->name : null;
      $cache->save($key, $x);
      return $name;
    }
  }
}