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

yipeiwu_com6年前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版微信小店接口开发实例

本文实例讲述了PHP版微信小店接口开发方法。分享给大家供大家参考,具体如下: 首先 大家可以去下一份小店开发的 API接口 因为 下面所有的 微信小店接口 数据格式 参数 API手册 里...

php使用QueryList轻松采集js动态渲染页面方法

QueryList使用jQuery的方式来做采集,拥有丰富的插件。下面来演示QueryList使用PhantomJS插件抓取JS动态创建的页面内容。 一、安装 使用Composer安装:...

redis+php实现微博(三)微博列表功能详解

本文实例讲述了redis+php实现微博列表功能。分享给大家供大家参考,具体如下: 个人主页显示微博列表(自己及关注人的微博列表) /*获取最新的50微博信息列表,列出自己发布的微博...

PHP使用NuSOAP调用Web服务的方法

本文实例讲述了PHP使用NuSOAP调用Web服务的方法。分享给大家供大家参考。具体如下: Steps: 1. Download nusoap library from internet...

PHP根据图片色界在不同位置加水印的方法

本文实例讲述了PHP根据图片色界在不同位置加水印的方法。分享给大家供大家参考。具体实现方法如下: function add_wm($nmw_water, $src_file, $ou...