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文件缓存类用法实例分析内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

您可能有感兴趣的文章
PHP性能优化案例分享

PHP实现短信验证码的发送次数限制

PHP中的异常处理机制深入讲解

PHP常见七种算法合集代码实例

PHP微信扫描二维码关注公众号后自动登录第三方网站