【问题标题】:beforeFind() in Yii ActiveRecord and cacheYii ActiveRecord 中的 beforeFind() 和缓存
【发布时间】:2018-09-10 15:12:58
【问题描述】:

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

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

不好看也不琐碎,导致很多分支。

【问题讨论】:

    标签: activerecord yii redis


    【解决方案1】:

    您不应为此使用beforeFind()。除了实现中的技术问题外,您可能会因此而产生许多副作用并且难以调试错误。那是因为缓存可能已经过时并且许多内部 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;
    }
    

    您可以将此类方法添加到 trait 并在多个模型中重用它。那么你只需要:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      • 2014-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多