1. <?php
  2. /**
  3.  * 文件缓存类
  4.  * @author flynetcn
  5.  */
  6. class FileCache
  7. {
  8.     const CACHE_DIR = '/tmp/cache';
  9.     private $dir;
  10.     private $expire = 300;

  11.     /**
  12.      * @param $strDir 缓存子目录(方便清cache)
  13.      */
  14.     function __construct($strDir='')
  15.     {
  16.         if ($strDir) {
  17.             $this->dir = self::CACHE_DIR.'/'.$strDir;
  18.         }
  19.     }

  20.     private function getFileName($strKey)
  21.     {
  22.         return $this->dir.'/'.$strKey;
  23.     }

  24.     public function setExpire($intSecondNum)
  25.     {
  26.         if ($intSecondNum<10 || !is_int($intSecondNum)) {
  27.             return false;
  28.         }
  29.         $this->expire = $intSecondNum;
  30.         return true;
  31.     }

  32.     public function getExpire()
  33.     {
  34.         return $this->expire;
  35.     }

  36.     public function get($strKey)
  37.     {
  38.         $strFileName = $this->getFileName($strKey);
  39.         if (!@file_exists($strFileName)) {
  40.             return false;
  41.         }
  42.         if (filemtime($strFileName) < (time()-$this->expire)) {
  43.             return false;
  44.         }
  45.         $intFileSize = filesize($strFileName);
  46.         if ($intFileSize == 0) {
  47.             return false;
  48.         }
  49.         if (!$fp = @fopen($strFileName, 'rb')) {
  50.             return false;
  51.         }
  52.         flock($fp, LOCK_SH);
  53.         $cacheData = unserialize(fread($fp, $intFileSize));
  54.         flock($fp, LOCK_UN);
  55.         fclose($fp);
  56.         return $cacheData;
  57.     }

  58.     public function set($strKey, $cacheData)
  59.     {
  60.         if (!is_dir($this->dir)) {
  61.             if (!@mkdir($this->dir, 0755, true)) {
  62.                 trigger_error("mkdir({$this->dir}, 0755, true) failed", E_USER_ERROR);
  63.                 return false;
  64.             }
  65.         }
  66.         $strFileName = $this->getFileName($strKey);
  67.         if (@file_exists($strFileName)) {
  68.             $intMtime = filemtime($strFileName);
  69.         } else {
  70.             $intMtime = 0;
  71.         }
  72.         if (!$fp = fopen($strFileName,'wb')) {
  73.             return false;
  74.         }
  75.         if (!flock($fp, LOCK_EX+LOCK_NB)) {
  76.             fclose($fp);
  77.             return false;
  78.         }
  79.         if (time() - $intMtime < 1) {
  80.             flock($fp, LOCK_UN);
  81.             fclose($fp);
  82.             return false;
  83.         }
  84.         fseek($fp, 0);
  85.         ftruncate($fp, 0);
  86.         fwrite($fp, serialize($cacheData));
  87.         flock($fp, LOCK_UN);
  88.         fclose($fp);
  89.         @chmod($strFileName, 0755);
  90.         return true;
  91.     }
  92. }

09-22 01:50