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类常量的使用详解

可以把在类中始终保持不变的值定义为常量。在定义和使用常量的时候不需要使用 $ 符号。 常量的值必须是一个定值,不能是变量,类属性,数学运算的结果或函数调用。 接口(interface)中...

php合并数组array_merge函数运算符加号与的区别

array_merge在参考手册中的说明如下: array_merge() 将两个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。 如果输入的数组中有...

PHP中explode函数和split函数的区别小结

一、前言 之所以做这个,是因为这两个函数的作用很像,都是把字符串转换成数组。 二、explode 从下面的例子可以看出,生成的数组是有对应的顺序的。 $pizza = "piece1...

PHP在特殊字符前加斜杠的实现代码

复制代码 代码如下: <?php $zongzi = "asdfasdf(asdfasdf?asfdadsf)"; echo $zongzi = quotemeta($zongzi...

PHP中Memcache操作类及用法实例

本文实例讲述了PHP中Memcache操作类及用法。分享给大家供大家参考。具体分析如下: 复制代码 代码如下: <?php     ...