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文件锁函数flock()详细介绍

文件操作系统是在网络环境下完成的,可能有多个客户端用户在同一个时刻对服务器上的同一个文件访问。当这种并发访问产生时,很可能会破坏文件中。例如一个用户正在向文件中写入数据,当还没有写完时,...

PHP中提问频率最高的11个面试题和答案

你是否正在准备寻找一份PHP开发的工作,并且也在寻找一些关于PHP的面试题及答案?本文为大家分享了一些被提问频率最高的11个PHP面试题,以及对应的常规回答,每个公司都有自己的面试标准,...

PHP-FPM运行状态的实时查看及监控详解

PHP-FPM运行状态的实时查看及监控详解

前言 大家都知道PHP-FPM内置了状态页,开启后可查看PHP-FPM的详细运行状态,给PHP-FPM优化带来帮助。 打开php-fpm.conf,配置php-fpm状态页选项 p...

php常用字符函数实例小结

本文实例总结了php常用字符函数。分享给大家供大家参考,具体如下: 1. string substr(string  $string, int $start &nbs...

学习php设计模式 php实现建造者模式

学习php设计模式 php实现建造者模式

建造者模式可以让一个产品的内部表象和和产品的生产过程分离开,从而可以生成具有不同内部表象的产品。 一、Builder模式结构图   二、Builder模式中主要角色 抽象建造...