缓存类是我们开发应用中会常用使用到的功能,下面我来给大家整理几个php文件缓存类了,各个文件缓存类写法不同,但在性能上会有区别,有兴趣测试的朋友可测试一下这些缓存类吧.
例1,代码如下:
- <?php
- $fzz = new fzz_cache;
- $fzz->kk = $_SERVER;
-
- print_r($fzz->kk);
-
-
-
- var_dump(isset($fzz->kk));
-
-
-
- class fzz_cache{
- public $limit_time = 20000;
- public $cache_dir = "data";
-
-
- function __set($key , $val){
- $this->_set($key ,$val);
- }
-
- function _set($key ,$val,$limit_time=null){
- $limit_time = $limit_time ? $limit_time : $this->limit_time;
- $file = $this->cache_dir."/".$key.".cache";
- $val = serialize($val);
- @file_put_contents($file,$val) or $this->error(__line__,"fail to write in file");
- @chmod($file,0777);
- @touch($file,time()+$limit_time) or $this->error(__line__,"fail to change time");
- }
-
-
-
- function __get($key){
- return $this->_get($key);
- }
- function _get($key){
- $file = $this->cache_dir."/".$key.".cache";
- if (@filemtime($file)>=time()){
- return unserialize(file_get_contents($file));
- }else{
- @unlink($file) or $this->error(__line__,"fail to unlink");
- return false;
- }
- }
-
-
-
- function __unset($key){
- return $this->_unset($key);
- }
- function _unset($key){
- if (@unlink($this->cache_dir."/".$key.".cache")){
- return true;
- }else{
- return false;
- }
- }
-
-
-
- function __isset($key){
- return $this->_isset($key);
- }
- function _isset($key){
- $file = $this->cache_dir."/".$key.".cache";
- if (@filemtime($file)>=time()){
- return true;
- }else{
- @unlink($file) ;
- return false;
- }
- }
-
-
-
- function clear(){
- $files = scandir($this->cache_dir);
- foreach ($files as $val){
- if (filemtime($this->cache_dir."/".$val)<time()){
- @unlink($this->cache_dir."/".$val);
- }
- }
- }
-
-
-
- function clear_all(){
- $files = scandir($this->cache_dir);
- foreach ($files as $val){
- @unlink($this->cache_dir."/".$val);
- }
- }
-
- function error($msg,$debug = false) {
- $err = new Exception($msg);
- $str = "<pre>
- <span style='color:red'>error:</span>
- ".print_r($err->getTrace(),1)."
- </pre>";
- if($debug == true) {
- file_put_contents(date('Y-m-d H_i_s').".log",$str);
- return $str;
- }else{
- die($str);
- }
- }
- }
- ?>
例2.从CI社区的stblog和CI的file_helper类中提取出来的php文件缓存类,一个简单的基于文件的key->value缓存类。
这个类可以用来缓存一些基本信息,比如博客的header,footer,sidebar中的一些不经常变化,从数据库中取出的内容,取数据前先判断文件缓存中的内容是否过期,如果没过期取出来,过期了则连接数据库查询,并将结果重新写入文件缓存,更新过期时间。跟memcache使用类似,不过更方便。用在一些小的应用上足够了...代码如下:
- <?php
- define('DIRECTORY_SEPARATOR','/');
- define('FOPEN_WRITE_CREATE_DESTRUCTIVE','wb');
- define('FOPEN_WRITE_CREATE','ab');
- define('DIR_WRITE_MODE', 0777);
- class FileCache {
-
-
-
-
-
-
-
- private $_cache_path;
-
-
-
-
-
-
-
- private $_cache_expire;
-
-
-
-
-
-
-
- public function __construct($expire, $cache_path)
- {
- $this->_cache_expire = $expire;
- $this->_cache_path = $cache_path;
- }
-
-
-
-
-
-
-
-
- private function _file($key)
- {
- return $this->_cache_path . md5($key);
- }
-
-
-
-
-
-
-
-
-
- public function set($key, $data)
- {
- $value = serialize($data);
-
- $file = $this->_file($key);
-
- return $this->write_file($file, $value);
- }
-
-
-
-
-
-
-
-
- public function get($key)
- {
- $file = $this->_file($key);
-
-
- if (!file_exists($file) || !$this->is_really_writable($file))
- {
- return false;
- }
-
-
- if ( time() < (filemtime($file) + $this->_cache_expire) )
- {
-
- $data = $this->read_file($file);
-
- if(FALSE !== $data)
- {
- return unserialize($data);
- }
-
- return FALSE;
- }
-
-
- @unlink($file);
- return FALSE;
- }
-
- function read_file($file)
- {
- if ( ! file_exists($file))
- {
- return FALSE;
- }
-
- if (function_exists('file_get_contents'))
- {
- return file_get_contents($file);
- }
-
- if ( ! $fp = @fopen($file, FOPEN_READ))
- {
- return FALSE;
- }
-
- flock($fp, LOCK_SH);
-
- $data = '';
- if (filesize($file) > 0)
- {
- $data =& fread($fp, filesize($file));
- }
-
- flock($fp, LOCK_UN);
- fclose($fp);
-
- return $data;
- }
-
- function write_file($path, $data, $mode = FOPEN_WRITE_CREATE_DESTRUCTIVE)
- {
- if ( ! $fp = @fopen($path, $mode))
- {
- return FALSE;
- }
-
- flock($fp, LOCK_EX);
- fwrite($fp, $data);
- flock($fp, LOCK_UN);
- fclose($fp);
-
- return TRUE;
- }
- function is_really_writable($file)
- {
-
- if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE)
- {
- return is_writable($file);
- }
-
-
-
- if (is_dir($file))
- {
- $file = rtrim($file, '/').'/'.md5(rand(1,100));
-
- if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
- {
- return FALSE;
- }
-
- fclose($fp);
- @chmod($file, DIR_WRITE_MODE);
- @unlink($file);
- return TRUE;
- }
- elseif (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
- {
- return FALSE;
- }
-
- fclose($fp);
- return TRUE;
- }
- }
- $cache = new FileCache(30,'cache/');
- $cache->set('test','this is a test.');
- print $cache->get('test');
-
- ?>
例3.自己觉得很好用的php文件缓存,代码如下:
- <?php
- class cache
- {
- private static $_instance = null;
-
- protected $_options = array(
- 'cache_dir' => "./",
- 'file_name_prefix' => 'cache',
- 'mode' => '1',
- );
-
-
-
-
-
-
- public static function getInstance()
- {
- if(self::$_instance === null)
- {
- self::$_instance = new self();
- }
- return self::$_instance;
- }
-
-
-
-
-
-
-
- public static function get($id)
- {
- $instance = self::getInstance();
-
-
- if(!$instance->has($id))
- {
- return false;
- }
-
- $file = $instance->_file($id);
-
- $data = $instance->_fileGetContents($file);
-
- if($data['expire'] == 0 || time() < $data['expire'])
- {
- return $data['contents'];
- }
- return false;
- }
-
-
-
-
-
-
-
-
- public static function set($id, $data, $cacheLife = 0)
- {
- $instance = self::getInstance();
-
- $time = time();
- $cache = array();
- $cache['contents'] = $data;
- $cache['expire'] = $cacheLife === 0 ? 0 : $time + $cacheLife;
- $cache['mtime'] = $time;
-
- $file = $instance->_file($id);
-
- return $instance->_filePutContents($file, $cache);
- }
-
-
-
-
-
-
-
- public static function delete($id)
- {
- $instance = self::getInstance();
-
- if(!$instance->has($id))
- {
- return false;
- }
- $file = $instance->_file($id);
-
- return unlink($file);
- }
-
-
-
-
-
-
-
- public static function has($id)
- {
- $instance = self::getInstance();
- $file = $instance->_file($id);
-
- if(!is_file($file))
- {
- return false;
- }
- return true;
- }
-
-
-
-
-
-
- protected function _file($id)
- {
- $instance = self::getInstance();
- $fileNmae = $instance->_idToFileName($id);
- return $instance->_options['cache_dir'] . $fileNmae;
- }
-
-
-
-
-
-
-
- protected function _idToFileName($id)
- {
- $instance = self::getInstance();
- $prefix = $instance->_options['file_name_prefix'];
- return $prefix . '---' . $id;
- }
-
-
-
-
-
-
-
- protected function _fileNameToId($fileName)
- {
- $instance = self::getInstance();
- $prefix = $instance->_options['file_name_prefix'];
- return preg_replace('/^' . $prefix . '---(.*)$/', '$1', $fileName);
- }
-
-
-
-
-
-
-
-
- protected function _filePutContents($file, $contents)
- {
- if($this->_options['mode'] == 1)
- {
- $contents = serialize($contents);
- }
- else
- {
- $time = time();
- $contents = "<?phpn".
- " // mktime: ". $time. "n".
- " return ".
- var_export($contents, true).
- "n?>";
- }
-
- $result = false;
- $f = @fopen($file, 'w');
- if ($f) {
- @flock($f, LOCK_EX);
- fseek($f, 0);
- ftruncate($f, 0);
- $tmp = @fwrite($f, $contents);
- if (!($tmp === false)) {
- $result = true;
- }
- @fclose($f);
- }
- @chmod($file,0777);
- return $result;
- }
-
-
-
-
-
-
-
- protected function _fileGetContents($file)
- {
- if(!is_file($file))
- {
- return false;
- }
-
- if($this->_options['mode'] == 1)
- {
- $f = @fopen($file, 'r');
- @$data = fread($f,filesize($file));
- @fclose($f);
- return unserialize($data);
- }
- else
- {
- return include $file;
- }
- }
-
-
-
-
- protected function __construct()
- {
-
- }
-
-
-
-
-
-
-
- public static function setCacheDir($path)
- {
- $instance = self::getInstance();
- if (!is_dir($path)) {
- exit('file_cache: ' . $path.' 不是一个有效路径 ');
- }
- if (!is_writable($path)) {
- exit('file_cache: 路径 "'.$path.'" 不可写');
- }
-
- $path = rtrim($path,'/') . '/';
- $instance->_options['cache_dir'] = $path;
-
- return $instance;
- }
-
-
-
-
-
-
-
- public static function setCachePrefix($prefix)
- {
- $instance = self::getInstance();
- $instance->_options['file_name_prefix'] = $prefix;
- return $instance;
- }
-
-
-
-
-
-
-
- public static function setCacheMode($mode = 1)
- {
- $instance = self::getInstance();
- if($mode == 1)
- {
- $instance->_options['mode'] = 1;
- }
- else
- {
- $instance->_options['mode'] = 2;
- }
-
- return $instance;
- }
-
-
-
-
-
- public static function flush()
- {
- $instance = self::getInstance();
- $glob = @glob($instance->_options['cache_dir'] . $instance->_options['file_name_prefix'] . '--*');
-
- if(emptyempty($glob))
- {
- return false;
- }
-
- foreach ($glob as $v)
- {
- $fileName = basename($v);
- $id = $instance->_fileNameToId($fileName);
- $instance->delete($id);
- }
- return true;
- }
- }
-
-
- cache::setCachePrefix('core');
- cache::setCacheDir('./cache');
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- cache::setCacheMode('2');
-
- if(!$row = cache::get('zj2'))
- {
-
- $array = array(1,2,3,34,5,6,6);
- $row = cache::set('zj2',$array);
- }
-
-
- print_r($row);
-
- 件缓存 class
-
- <?php
-
-
-
-
-
- class cache
- {
- const FILE_LIFE_KEY = 'FILE_LIFE_KEY';
-
- const CLEAR_ALL_KEY = 'CLEAR_ALL';
-
- static $_instance = null;
-
- protected $_options = array(
- 'cache_dir' => './cache',
- 'file_locking' => true,
- 'file_name_prefix' => 'cache',
- 'cache_file_umask' => 0777,
- 'file_life' => 100000
- );
-
- static function &getInstance($options = array())
- {
- if(self::$_instance === null)
- {
- self::$_instance = new self($options);
- }
- return self::$_instance;
- }
-
-
-
-
-
-
- static function &setOptions($options = array())
- {
- return self::getInstance($options);
- }
-
-
-
-
-
-
- private function __construct($options = array())
- {
- if ($this->_options['cache_dir'] !== null) {
-
- $dir = rtrim($this->_options['cache_dir'],'/') . '/';
- $this->_options['cache_dir'] = $dir;
-
- if (!is_dir($this->_options['cache_dir'])) {
- mkdir($this->_options['cache_dir'],0777,TRUE);
- }
- if (!is_writable($this->_options['cache_dir'])) {
- exit('file_cache: 路径 "'. $this->_options['cache_dir'] .'" 不可写');
- }
-
- } else {
- exit('file_cache: "options" cache_dir 不能为空 ');
- }
- }
-
-
-
-
-
-
- static function setCacheDir($value)
- {
- $self = & self::getInstance();
-
- if (!is_dir($value)) {
- exit('file_cache: ' . $value.' 不是一个有效路径 ');
- }
- if (!is_writable($value)) {
- exit('file_cache: 路径 "'.$value.'" 不可写');
- }
-
- $value = rtrim($this->_options['cache_dir'],'/') . '/';
-
- $self->_options['cache_dir'] = $value;
- }
-
-
-
-
-
-
-
-
- static function save($data, $id = null, $cache_life = null)
- {
- $self = & self::getInstance();
- if (!$id) {
- if ($self->_id) {
- $id = $self->_id;
- } else {
- exit('file_cache:save() id 不能为空!');
- }
- }
- $time = time();
-
- if($cache_life) {
- $data[self::FILE_LIFE_KEY] = $time + $cache_life;
- }
- elseif
- ($cache_life != 0){
- $data[self::FILE_LIFE_KEY] = $time + $self->_options['file_life'];
- }
-
- $file = $self->_file($id);
-
- $data = "<?phpn".
- " // mktime: ". $time. "n".
- " return ".
- var_export($data, true).
- "n?>"
- ;
-
- $res = $self->_filePutContents($file, $data);
- return $res;
- }
-
-
-
-
-
-
-
-
- static function load($id)
- {
- $self = & self::getInstance();
- $time = time();
-
- if (!$self->test($id)) {
-
- return false;
- }
-
-
- $clearFile = $self->_file(self::CLEAR_ALL_KEY);
-
- $file = $self->_file($id);
-
-
- if(is_file($clearFile) && filemtime($clearFile) > filemtime($file))
- {
- return false;
- }
-
- $data = $self->_fileGetContents($file);
- if(emptyempty($data[self::FILE_LIFE_KEY]) || $time < $data[self::FILE_LIFE_KEY]) {
- unset($data[self::FILE_LIFE_KEY]);
- return $data;
- }
- return false;
- }
-
-
-
-
-
-
-
-
- protected function _filePutContents($file, $string)
- {
- $self = & self::getInstance();
- $result = false;
- $f = @fopen($file, 'ab+');
- if ($f) {
- if ($self->_options['file_locking']) @flock($f, LOCK_EX);
- fseek($f, 0);
- ftruncate($f, 0);
- $tmp = @fwrite($f, $string);
- if (!($tmp === false)) {
- $result = true;
- }
- @fclose($f);
- }
- @chmod($file, $self->_options['cache_file_umask']);
- return $result;
- }
-
-
-
-
-
-
-
- protected function _file($id)
- {
- $self = & self::getInstance();
- $fileName = $self->_idToFileName($id);
- return $self->_options['cache_dir'] . $fileName;
- }
-
-
-
-
-
-
-
- protected function _idToFileName($id)
- {
- $self = & self::getInstance();
- $self->_id = $id;
- $prefix = $self->_options['file_name_prefix'];
- $result = $prefix . '---' . $id;
- return $result;
- }
-
-
-
-
-
-
-
- static function test($id)
- {
- $self = & self::getInstance();
- $file = $self->_file($id);
-
- if (!is_file($file)) {
- return false;
- }
-
- return true;
- }
-
-
-
-
-
-
-
- protected function _fileGetContents($file)
- {
- if (!is_file($file)) {
- return false;
- }
- return include $file;
- }
-
-
-
-
-
-
- static function clear()
- {
- $self = & self::getInstance();
- $self->save('CLEAR_ALL',self::CLEAR_ALL_KEY);
- }
-
-
-
-
-
-
-
- static function del($id)
- {
- $self = & self::getInstance();
- if(!$self->test($id)){
-
- return false;
- }
- $file = $self->_file($id);
- return unlink($file);
- }
- }
-
- 存入数据
-
- <?php
- $config = array(
- 'name' => 'xiaojiong',
- 'qq' => '290747680',
- 'age' => '20',
- );
-
-
-
-
- cache::save($config,'config',0);
-
- 载入数据
-
- <?php
-
- $config = cache::load('config');
-
- 清空缓存
-
- <?php
-
- cache::del('config');
-
- cache::clear();
-
- cache信息配置
-
-
-
- $_options = array(
- 'cache_dir' => './cache',
- 'file_name_prefix' => 'cache',
- 'file_life' => 100000,
- );
- cache::setOptions($options);
-
-
- cache::save($arr,'arr');
-
-
- ?>
|