php文件缓存类用法实例分析

yipeiwu_com5年前PHP代码库

本文实例讲述了php文件缓存类用法。分享给大家供大家参考。具体如下:

<?php
/**
 * 简单的文件缓存类
 *
 */
class XZCache{
 // default cache time one hour
 var $cache_time = 3600;
 // default cache dir
 var $cache_dir = './cache';
 public function __construct($cache_dir=null, $cache_time=null){
  $this->cache_dir = isset($cache_dir) ? $cache_dir : $this->cache_dir;
  $this->cache_time = isset($cache_time) ? $cache_time : $this->cache_time;
 }
 public function saveCache ($key, $value){
  if (is_dir($this->cache_dir)){
   $cache_file = $this->cache_dir . '/xzcache_' . md5($key);
   $timedif = @(time() - filemtime($cache_file));
   if ($timedif >= $this->cache_time) {
    // cached file is too old, create new
    $serialized = serialize($value);
    if ($f = @fopen($cache_file, 'w')) {
     fwrite ($f, $serialized, strlen($serialized));
     fclose($f);
    }
   }
   $result = 1;
  }else{
   echo "Error:dir is not exist.";
   $result = 0;
  }
  return $result;
 }
 /**
  * @return array 
  *   0 no cache
  *    1 cached
  *    2 overdue
  */
 public function getCache ($key) {
  $cache_file = $this->cache_dir . '/xzcache_' . md5($key);
  if (is_dir($this->cache_dir) && is_file($cache_file)) {
   $timedif = @(time() - filemtime($cache_file));
   if ($timedif >= $this->cache_time) {
    $result['cached'] = 2;
   }else{
    // cached file is fresh enough, return cached array
    $result['value'] = unserialize(file_get_contents($cache_file));
    $result['cached'] = 1;
   }
  }else {
   echo "Error:no cache";
   $result['cached'] = 0;
  }
  return $result;
 }
} //end of class

用法示例如下:

$cache = new XZCache();
$key = 'global';
$value = $GLOBALS;
$cache->saveCache($key, $value);
$result = $cache->getCache($key);
var_dump($result);

希望本文所述对大家的php程序设计有所帮助。

相关文章

优化PHP程序的方法小结

1. If a method c++an be static, declare it static. Speed improvement is by a factor of 4. 如果一...

解析php中如何直接执行SHELL

$message=shell_exec("sudo /usr/local/webserver/nginx/sbin/nginx -t 2>&1");echo "运行结果:".$me...

PHP基于ICU扩展intl快速实现汉字转拼音及按拼音首字母分组排序的方法

本文实例讲述了PHP基于ICU扩展intl快速实现汉字转拼音及按拼音首字母分组排序的方法。分享给大家供大家参考,具体如下: ICU(International Components fo...

phplock(php进程锁) v1.0 beta1

在web开发中我们经常对我们的数据库耗时操作做缓存,但是可能出现一个陷阱,在缓存失效的一瞬间,大量的访问得到缓存失效的标示,都去后端查询数据库,导致同时大量的数据库耗时查询,出现数据库宕...

php中使用websocket详解

在PHP中,开发者需要考虑的东西比较多,从socket的连接、建立、绑定、监听等都需要开发者自己去操作完成,对于初学者来说,难度方面也挺大的,所以本文的思路如下: 1、socket协议的...