<?php
class Cache { private $cache_path;//path for the cache private $cache_expire;//seconds that the cache expires //cache constructor, optional expiring time and cache path public function Cache($exp_time=3600,$path){ $this->cache_expire=$exp_time; $this->cache_path=$path; $this->CreateFolder($path); } //returns the filename for the cache private function fileName($key){ return $this->cache_path.$key; } //creates new cache files with the given data, $key== name of the cache, data the info/values to store public 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 key public function get($key){ $filename = $this->fileName($key); if (!file_exists($filename) || !is_readable($filename)){//can't read the cache return 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 } public function CreateFolder($dir, $mode = 0777){ if (is_dir($dir) || @mkdir($dir, $mode)) return true; if (!self::CreateFolder(dirname($dir), $mode)) return false; return @mkdir($dir, $mode); }}?>用法如下:
<?php
include 'cache.class.php'; //引入缓存类
$cache_time = '86400'; //设置缓存时间
$cache_path = 'cache/'; //设置缓存路径
$cache_filename = 'cachefile'; //设置缓存文件名
$cache = new Cache($cache_time,$cache_path); //实例化一个缓存类
$key = $cache_filename; $value = $cache->get($key); if ($value == false) { $value = getDataFromDb(); //getDataFromDb是从数据库中读取数据的函数 $cache->put($key, $value); //写入缓存 } 得到$value就是想要的数据 ,根据需求自己写方法。?>