Yii 打造带有缓存功能的AR

继承AR类 重写 findByPk方法为pk  还有afterSave afterDelete

通过对象主键缓存其属性  在insert update delete 操作时候 都会自动更新缓存
还是挺方便的

public function afterDelete()
{
    $cache = $this->getCache();
    $cache->cdelete($this->cacheGroup(), $this->getPKValue());
    parent::afterDelete();
}

public function cacheGroup()
{
    return $this->tableName();
}

public function pk($value)
{
    $attr = $this->getCache()->cget($this->cacheGroup(), $value);
    if (!$attr) {
        $model = $this->findByPk($value);
        if ($model) {
            $attr = $model->getAttributes();
        }
        $this->getCache()->cset($this->cacheGroup(), $value, $attr = !empty($attr) ? $attr :
            MMemcache::NULL_VAR);
    } elseif (MMemcache::isNULL($attr)) {
        $model = null;
    } else {
        $model = $this->populateRecord($attr);
    }
    return $model;
}

public function afterSave()
{
    $cache = $this->getCache();
    $cache->cdelete($this->cacheGroup(), $this->getPKValue());
    if ($this->getIsNewRecord()) {
        $cache->cadd($this->tableName(), $this->getPKValue(), $this->getAttributes());
    } else {
        $cache->cadd($this->tableName(), $this->getPKValue(), $this->getAttributes());
    }
    parent::afterSave();
}

MMemcache 自己的情况实现

大家有好思路 多分享哦  这样Yii才会越来越强大 

From: http://hc1988.diandian.com/page/2?tag=yii

posted on 2013-11-30 20:52  imxiu  阅读(360)  评论(0编辑  收藏  举报

导航