PHP   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了PHP微信开发用Cache 解决数据缓存大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

PHP进行微信开发时,碰到access_token长久保存的问题,以前都是用框架里的Cache直接set、get一下就完了。现在没框架可用了,只好自己动手写一个cache暂时用。

这个Cache类用来缓存一些具有时效性的数据,比如微信基础接口的access_token、网页Auth验证的access_token等

下面的代码使用本地文件进行数据的缓存,

dir = "../cc/";
 //$cache->setCache("zhang","zhangsan",100);
 echo $cache->getCache("zhang");
 //$cache->removeCache("zhang");

$cache->setCache("liu","liuqi",100);
echo $cache->getCache("liu");

class Cache{
public $cacheFile = "cache.json"; //文件
public $dir = "./cach2/"; //目录

//缓存
public function setCache($name,$val,$expires_timE){
$file = $this->hasFile();
//字符串转数组
$str = file_get_contents($filE);
$arr = json_decode($str,truE);

//值为空,则移除该缓存
if(empty($val)){
unset($arr[$name]);
}else{
$arr[$name] = array("value"=>$val,"expires_time"=>$expires_time,"add_time"=>time());
}
//数组转字符串
$str = json_encode($arr);
file_put_contents($file,$str);
}
public function getCache($Name){
$file = $this->hasFile();

//字符串转数组
$allArr = json_decode($str,truE);
$arr = $allArr[$name];

if(!$arr || time() > ($arr["expires_time"] + $arr["add_time"])){
$this->removeCache($Name); //过期移除
return false;
}
return $arr["value"];
}
public function removeCache($Name){
$this->setCache($name,'',0);
}

private function hasFile(){
//如果不存在缓存文件,则创建一个
if(!file_exists($this->dir)){
mkdir($this->dir);
}
if(!file_exists($this->dir . $this->cacheFilE)){
touch($this->dir . $this->cacheFilE);
}
return $this->dir . $this->cacheFile;
}
}

大佬总结

以上是大佬教程为你收集整理的PHP微信开发用Cache 解决数据缓存全部内容,希望文章能够帮你解决PHP微信开发用Cache 解决数据缓存所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。