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 文件上传代码(限制jpg文件)

复制代码 代码如下:<?php /* 图片上传类  仅限JPG格式图片 */ class uploadFile { var $inputName; //input名称 v...

PHP获取真实客户端的真实IP

REMOTE_ADDR 是你的客户端跟你的服务器“握手”时候的IP。如果使用了“匿名代理”,REMOTE_ADDR将显示代理服务器的IP。 HTTP_CLIENT_IP 是代理服务器发送...

PHP实现多级分类生成树的方法示例

本文实例讲述了PHP实现多级分类生成树的方法。分享给大家供大家参考,具体如下: 条件,数据库里分类是按id,fid(父ID)实现多级分类的! 使用方法: $sql ="XXXXXX...

PHP实现的XML操作类【XML Library】

本文实例讲述了PHP实现的XML操作类。分享给大家供大家参考,具体如下: 这是一个接口程序,需要大量分析解析XML,PHP的xml_parse_into_struct()函数不能直接生成...

10个对初学者非常有用的PHP技巧

本文介绍一些关于改善和优化PHP代码的提示和技巧,供大家参考,具体内容如下 1.不要使用相对路径,要定义一个根路径 这样的代码行很常见: require_once('../../li...