最族
记一次判断错误所引起的缓存失败问题
2017-4-18 Veris


我习惯用empty来检测数据,今天碰到了个缓存失败问题,之前的代码如下:


// 根据分类动作获取应用列表
public function getListByAction($action=''){
$cacheName='appListByAction('.$action.')V1';
$appList=cache($cacheName);
if(empty($appList)){ //如果缓存未设置
$cid=Db::name('appCategory')->where('action',$action)->value('id');
$appModel=Db::name('app')->where('status',1);
if(!empty($cid)){
$appModel->where('cid',$cid);
}
$appList=$appModel->select();
cache($cacheName,$appList,604800); // 缓存一星期
}
return $appList;
}


我在缓存以下两个数据的时候都是的:




  1. appListByAction()V1


  2. appListByAction(show)V1



但是缓存appListByAction(sale)V1的时候出了问题,最终排查出了问题。



实际缓存存入是成功了,但是这个$appList的内容是个空数组,所以第二次再访问数据的时候,判断是否有缓存那出现问题了,empty支持判断为空的类型范围比较多,可以看如下:




  1. "" (an empty string)


  2. 0 (0 as an integer)


  3. 0.0 (0 as a float)


  4. "0" (0 as a string)


  5. NULL


  6. FALSE


  7. array() (an empty array)


  8. $var; (a variable declared, but without a value)



因为$appList=array(),empty($appList)为true,以,缓存操作又一次的被执行了。



我们只要将判断改为if($appList===false),注意这里用了恒等,确保阻止array()==false为true的情况发生

发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容