php 微信 code 缓存,PHP微信开发用Cache 解决数据缓存

本文介绍如何在无框架环境下,用PHP编写一个简单的Cache类,用于存储微信基础接口的access_token等时效性数据。通过本地文件操作实现缓存,包括set、get和remove操作,并可自定义缓存路径。

摘要:用php进行微信开发时,碰到access_token长久保存的问题,以前都是用框架里的Cache直接set、get一下就完了。现在没框架可用了,只好自己动手写一个cache暂时用。这个Cache类用来缓存一些具有时效性的数据,比如微信基础接口的access_token、网页Auth验证的access_token等下面的代码使用本地文件进行数据的缓存,//测试

$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微信开发用Cache 解决数据缓存请关注PHP中文网(www.php.cn)其它文章!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值