你现在的位置:首页 > opencart 正文

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

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);
    }
  }
}