PHP微信开发用Cache 解决数据缓存
来源: 阅读:707 次 日期:2016-08-16 14:45:45
温馨提示: 小编为您整理了“PHP微信开发用Cache 解决数据缓存”,方便广大网友查阅!

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

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

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

//测试

$cache = new Cache();

$cache->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;

}

}

上面的Cache类共有set、get、remove三种操作。另外还可以自定义缓存文件的保存路径,只要设置Cache的dir属性就可以了。

以上就是PHP 微信开发时数据缓存的方法,希望对大家的学习有所帮助.

更多信息请查看 网络编程
由于各方面情况的不断调整与变化, 提供的所有考试信息和咨询回复仅供参考,敬请考生以权威部门公布的正式信息和咨询为准!
关于我们| 联系我们| 人才招聘| 网站声明| 网站帮助| 非正式的简要咨询| 简要咨询须知| 加入群交流| 手机站点| 投诉建议
工业和信息化部备案号:滇ICP备2023014141号-1 云南省教育厅备案号:云教ICP备0901021 滇公网安备53010202001879号 人力资源服务许可证:(云)人服证字(2023)第0102001523号
云南网警备案专用图标
联系电话:0871-65317125(9:00—18:00) 获取招聘考试信息及咨询关注公众号:
咨询QQ:526150442(9:00—18:00) 版权所有:
云南网警报警专用图标
Baidu
map