程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php實現數據緩存程序

php實現數據緩存程序

編輯:關於PHP編程

<?php
/**
 * cache class
 */

class Cache {
 /**
  * cache path
  *
  * @var string
  */
 var $cache_path;
 /**
  * timeout
  *
  * @var integer
  */
 var $time = 60;
 
 /**
  * construct for this class
  *
  * @param string $cache_path
  * @return Cache
  */
 function Cache($cache_path = 'cache') {
  if(is_dir($cache_path)) {
   $this->cache_path = rtrim($cache_path,'/').'/';
  } else {
   die('cache dir is not exists.');
  }
 }
 
 /**
  * set timeout
  *
  * @param integer $time
  * @return boolean
  */
 function setTime($time) {
  if(isset($time) && is_integer($time)) {
   $this->time = $time;
   return true;
  } else {
   return false;
  }
 }
 
 /**
  * read cache
  *
  * @param string $cache_id
  * @return mixed
  */
 function read($cache_id) {
  $cache_file = $this->cache_path.$cache_id.'.cache';
  if(!file_exists($cache_file)) {
   return false;
  }
  $mtime = filemtime($cache_file);
  if((time() - $mtime) > $this->time) {
   return false;
  } else {
   $fp = fopen($cache_file,'r');
   $content = fread($fp,filesize($cache_file));
   fclose($fp);
   unset($fp);
   if($content) {
    return unserialize($content);
   } else {
    return false;
   }
  }
 }
 
 /**
  * write cache in a file
  *
  * @param string $content
  * @param string $cache_id
  * @return boolean
  */
 function write($content,$cache_id) {
  $cache_file = $this->cache_path.$cache_id.'.cache';
  if(file_exists($cache_file)) {
   @unlink($cache_file);
  }
  $fp = fopen($cache_file,'w');
  $content = serialize($content);
  if(fwrite($fp,$content)) {
   fclose($fp);
   unset($fp);
   return true;
  } else {
   fclose($fp);
   unset($fp);
   return false;
  }
 }
 
 /**
  * clean all cache
  *
  * @param string $path
  * @return boolean
  */
 function cleanCache($path = 'cache') {
  if(is_dir($path)) {
   $path = rtrim($path,'/').'/';
   $handler = opendir($path);
   while (($f = readdir($handler)) !== false) {
    if(!is_dir($f)) {
     if($f != '.' && $f != '..') {
      @unlink($path.$f);
     }
    } else {
     $this->cleanCache($f);
    }
   }
  } else {
   return false;
  }
 }
}

?>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved