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