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程序设计有所帮助。

相关文章

thinkphp5.0自定义验证规则使用方法

我们在用thinkphp5.0时候,经常要自定义验证规则,这个写法与tp以前的版本有所区别,小编今天带来大家一起来学习一下5.0下验证规则的使用方法。 在thinkphp5中定义$rul...

php 多关键字 高亮显示实现代码

php 多关键字 高亮显示实现代码

项目结构: 开始搜索:   这里搜索关键字("大""这") 搜索结果:  高亮显示 项目所需数据库结构: 实现代码: conn.php 复制代码 代码...

PHP中十六进制颜色与RGB颜色值互转的方法

16进制的颜色值通常表示为#FFFFFF,当前也有缩减为#FFF,前提是两位两位必需相同,例如#FEFEFE这种,就不能进行缩减。而RGB的颜色格式是由3组0~255的数字构成,分别代表...

几款免费开源的不用数据库的php的cms

1、MuCMS一个小型,平台独立的内容管理系统适用于非交互式网站(网站只发布信息)。它对系统要求非常低,只需要Apache+PHP。没有使用数据库。它具有安全,快速,易用等特点。官方网站...

解析php中用PHPMailer来发送邮件的示例(126.com的例子)

<?phprequire_once('../class.phpmailer.php');$mail= new PHPMailer();$body= "我终于发送邮件成功了!呵呵!g...