php製作file cache 檔案簡易暫存

網站有可能因為抓取檔案時抓取時間太久,造成網頁速度變慢

所以增加一個小程式

!!!! 放置暫存檔案的該目錄一定要有apache讀寫權限 !!!!

可以參考 :在centos7給予apache設定某資料夾權限

以下為程式碼:

<?php

class Cache {

  //緩存目錄
  protected static $dir = '/root/temp/phpcache/'; #該目錄一定要有apache讀寫權限
  
  # 設置緩存
  
  static function set($key, $value, $time = 0)
  {
    $file = self::_file_name($key);

    //檢測是否有該緩存
    if (is_file($file)) {
      unlink($file);
    }
    //編輯緩存時間
    if ($time != '0') {
      $cache_over_time = time() + $time;
    } else {
      $cache_over_time = 0;
    }

    $data = [$key => $value, 'cache_over_time' => $cache_over_time];
    $data = serialize($data);
    //寫入緩存
    if (file_put_contents($file, $data) === false) {
      throw new Exception("temp 緩存目錄沒有寫入權限");
    }
  }

   # 取得緩存
  static function get($key) {
    $file = self::_file_name($key);

    //檢測是否有該緩存
    if (!is_file($file)) {
      return null;
    }
    //檢測緩存是否過期
    if (self::file_over_time($file)) {
      unlink($file);
      return null;
    }

    $data = file_get_contents($file);
    $data = unserialize($data);
    return $data[$key];
  }

   # 刪除緩存
   
  static function del($key) {
    $file = self::_file_name($key);
    if (is_file($file)) {
      unlink($file);
    }
  }

   #清空緩存
  static function clear()
  {
    $path = self::$dir . '*.php';
    foreach (glob($path) as $v) {
      unlink($v);
    }
  }

  /**
   * 檢測文件是否過期
   */
  protected static function file_over_time($file)
  {
    $data = file_get_contents($file);
    $data = unserialize($data);
    if ($data['cache_over_time'] < time() && $data['cache_over_time'] != '0') {
      return true;
    } else {
      return false;
    }
  }

 
  # 獲得文件名稱
  
  protected static function _file_name($key)
  {
    $file = self::$dir . $key . '.php';
    return $file;
  }
}
?>