介绍
这篇文章给大家介绍利用PHP实现一个缓存类,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
<强>使用说明:
1,实例化
强> $缓存=新的缓存();
<强> 2,设置缓存时间和缓存目录
>强劲美元缓存=new缓存(60 & # 39;/any_other_path & # 39;);
第一个参数是缓存秒数,第二个参数是缓存路径,根据需要配置。
默认情况下,缓存时间是3600秒,缓存目录是缓存/
<强> 3,读取缓存
强> value=https://www.yisu.com/zixun/缓存->美元(“data_key”);
<强> 4,写入缓存
强> value=https://www.yisu.com/zixun/缓存->把美元(“data_key”、“data_value”);
<强>完整实例:强>
cache 美元;=,new 缓存(),, ,//从缓存从读取键值,key 美元;的数据, $ values =,缓存→美元(美元键);, ,//如果没有缓存数据, if (values 美元;==,false), {,//insert code 这里……,//写入键值,key 美元;的数据, 缓存→美元把(键,美元,美元值),, {},else //insert code 这里……, }
<强> Cache.class。php 强>
& lt; ? php {class Cache private cache_path美元;//path  for 从而cache private cache_expire美元;//seconds  that 从而cache expires ,//cache 构造函数,optional expiring time 以及cache path public function 缓存(exp_time=3600美元,美元路径=盎捍??{, $ this→cache_expire=$ exp_time;, $ this→cache_path=$路径;, }, ,//returns 从而filename for 从而cache private function 文件名(键){, return 这→美元cache_path.md5(键)美元;, }, ,//creates new  cache files  with 从而given 数据,美元关键==,name of 从而缓存,data 从而信息/values 用store public function put(键,美元,美元数据){, $ values =,序列化(元数据),, filename 美元;=,$ this→文件名(键)美元;, file 美元;=,fopen(文件名,美元,& # 39;w # 39;),, 美元if (文件){//able 用create 从而file 写入文件(文件,美元,美元值),, 文件关闭(文件),, }, else return 虚假, }, ,//returns cache  for 从而given key public function get(键)美元{, filename 美元;=,$ this→文件名(键)美元;, if (! file_exists(文件名)美元,| |,! is_readable ($ filename)){//停下来# 39;t read 从而cache return 虚假, }, if (,时间()& lt;, (filemtime(文件名),+,$ this→cache_expire),), {//cache for 从而key not expired $ file =, fopen(文件名,美元,“r");//, read data file 美元if (文件){//able 用open 从而file data 美元;=,从文件中读($文件,文件大小(文件名)美元),, 文件关闭(文件),, return unserialize(元数据);//return 从而values }, else return 虚假, }, else return 假;//was  expired 你need 用create new }, }, ?在
关于利用PHP实现一个缓存类就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看的到。