代码之家  ›  专栏  ›  技术社区  ›  Velaro

Yii ActiveRecord和cache中的beforeFind()

  •  0
  • Velaro  · 技术社区  · 6 年前

    在一些模型类中,我想实现缓存。我想这样做:

    UsersModel::model()->findByAttributes([...])
    

    在那个类中,我想重写方法 beforeFind() 首先将请求发送到缓存服务器,但该方法似乎不接受任何附加参数,也没有具有属性的对象。

    在顶层代码中添加附加条件/检查,例如:

    $response = Yii::app()->cache->get('userUserLogin');
    if(empty($response) == true) {
        //fetch data from db and set to cache
        $userModel = UsersModel::model->findByAttributes([...])
        Yii::app()->cache->set('user' . $userModel->username, $userModel->getAttributes());
    }
    

    1 回复  |  直到 6 年前
        1
  •  1
  •   rob006    6 年前

    你不应该使用 beforeFind() 为了这个。除了实现中的技术问题之外,您可能会因此得到许多副作用和难以调试的bug。这是因为缓存可能已经过时,许多内部Yii逻辑可能依赖于以下假设: findByAttributes() (和其他方法)总是从数据库中获取新的数据。您也不能忽略缓存并直接从数据库获取模型。


    1使用 CActiveRecord::cache()

    $model = UsersModel::model()->cache(60)->findByAttributes([...])
    

    这将查询缓存结果60秒。

    2自定义帮助程序

    您可以添加自定义方法,这将简化使用缓存的活动记录:

    public static function findByAttributesFromCache($attributes = []) {
        $result = Yii::app()->cache->get(json_encode($attributes));
        if ($result === false) {
            //fetch data from db and set to cache
            $result = static::model()->findByAttributes($attributes);
            Yii::app()->cache->set(json_encode($attributes), $result, 60);
        }
    
        return $result;
    }
    

    $userModel = UsersModel::findByAttributesFromCache([...]);