简单至极的 PHP 缓存类
来源:互联网 发布:3g网络和2g网络的区别 编辑:程序博客网 时间:2024/06/06 10:01
出处:http://www.mangguo.org/the-simple-php-cache-class/
记录一下,方便以后研究,未经试用,以下原文
网上关于 PHP 缓存类的资料很多,不过这个类应该是我见过功能满足需求,但又无比简洁的一个。废话不多说,直接看代码吧!
使用说明:
1、实例化
$cache = new Cache();
2、设置缓存时间和缓存目录
$cache = new Cache(60, '/any_other_path/');
第一个参数是缓存秒数,第二个参数是缓存路径,根据需要配置。
默认情况下,缓存时间是 3600 秒,缓存目录是 cache/
3、读取缓存
$value = $cache->get('data_key');
4、写入缓存
$value = $cache->put('data_key', 'data_value');
完整实例:
$cache = new Cache();//从缓存从读取键值 $key 的数据$values = $cache->get($key);//如果没有缓存数据if ($values == false) {//insert code here...//写入键值 $key 的数据$cache->put($key, $values);} else {//insert code here...}
Cache.class.php
<?phpclass Cache {private $cache_path;//path for the cacheprivate $cache_expire;//seconds that the cache expires//cache constructor, optional expiring time and cache pathpublic function Cache($exp_time=3600,$path="cache/"){$this->cache_expire=$exp_time;$this->cache_path=$path;}//returns the filename for the cacheprivate function fileName($key){return $this->cache_path.md5($key);}//creates new cache files with the given data, $key== name of the cache, data the info/values to storepublic function put($key, $data){$values = serialize($data);$filename = $this->fileName($key);$file = fopen($filename, 'w'); if ($file){//able to create the file fwrite($file, $values); fclose($file); } else return false;}//returns cache for the given keypublic function get($key){$filename = $this->fileName($key);if (!file_exists($filename) || !is_readable($filename)){//can't read the cachereturn false;}if ( time() < (filemtime($filename) + $this->cache_expire) ) {//cache for the key not expired$file = fopen($filename, "r");// read data file if ($file){//able to open the file $data = fread($file, filesize($filename)); fclose($file); return unserialize($data);//return the values } else return false;}else return false;//was expired you need to create new }}?>
- 简单至极的 PHP 缓存类
- 一个简单至极的PHP缓存类代码
- PHP简单的缓存类
- 简单实用的PHP文本缓存类
- 简单高效的 PHP 文件缓存类
- PHP的UTF-8中文转拼音处理类(性能已优化至极致)
- PHP的UTF-8中文转拼音处理类(性能已优化至极致)
- 12c 简单至极的静默方式创建数据库
- ABAP ALV弹出框POPUP-简单至极的做法
- 关于php缓存技术的简单总结
- php的缓存类
- 一个PHP简单文件缓存类
- php简单缓存学习
- .net简单的缓存类
- 【PHP】静态缓存简单应用
- 你是否为【清理缓存】而烦恼至极
- 一个实用的PHP缓存类
- 多菜鸟 的 php缓存类
- 到底谁吃亏了?
- 求1000以内的偶数和
- eclipse-PHP中操作js文件时经常卡住的解决方法
- 闲得无聊之插入排序
- 安装hadoop1.0.3笔记
- 简单至极的 PHP 缓存类
- latex绘制流程图及中文显示问题
- hdu 1237 简单计算器
- 小木马的伤感日志:希望这辈子你会比我幸福
- WebKit flash播放
- 3.10 循环语句
- HTTP 411 ERROR CODE的处理方法
- 分数的累加
- 判断 iframe 是否加载完成的完美方法