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

相关文章

解析htaccess伪静态的规则

利用htaccess文件可以很好的进行站点伪静态,并且形成的目标地址与真正的静态页面几乎一模一样,如wangqu.html等,伪静态可以非常好的结合SEO来提高站点的排名,并且也能给人一...

PHP操作MongoDB GridFS 存储文件的详解

复制代码 代码如下:<?php //初始化gridfs $conn = new Mongo(); //连接MongoDB $db = $conn->photos; //选择数...

php调用新浪短链接API的方法

本文实例讲述了php调用新浪短链接API的方法。分享给大家供大家参考。具体方法如下: 复制代码 代码如下:<?php //Sina App_Key define('SINA...

关于php fread()使用技巧

说明 string fread ( int handle, int length ) fread() 从文件指针 handle 读取最多 length 个字节。该函数在读取完最多 len...

PHP如何读取由JavaScript设置的Cookie

cookie在开发中使用的非常多,但如果是使用JavaScript设置cookie然后使用PHP读取出来如何实现呢?即PHP与JavaScript下Cookie的交互使用是否可行呢?...