从opencart里面抠出来一个数据缓存类,看着感觉不错

来源:互联网 发布:nginx windows教程 编辑:程序博客网 时间:2024/05/16 09:08
class cache {
  var $maxlifetime = 3600;

  function cache() {
    if (!is_writable(DIR_CACHE)) {
      exit('Error: Could not write to cache directory!');
    }

    foreach (glob(DIR_CACHE . 'cache.*') as $file) {
      $array = explode('.', end(explode('/', $file)));

      if ($array[2] < time()) {
        $this->delete($array[1]);
      }
    }
  }

  function set($key, $value) {
    $this->delete($key);

    $file = fopen(DIR_CACHE . 'cache.' . $key . '.' . (time() + $this->maxlifetime), 'a');

    fwrite($file, serialize($value));
    fclose($file);
  }

  function get($key) {
    foreach (glob(DIR_CACHE . 'cache.' . $key . '.*') as $cache) {
      $contents = fopen($cache, 'r');
      $result   = fread($contents, filesize($cache));
      fclose($contents);

      return unserialize($result);
    }
  }
 
  function delete($key) {
    foreach (glob(DIR_CACHE . 'cache.' . $key . '.*') as $file) {
      unlink($file);
    }
  }
}
 
原创粉丝点击