自己练手写的 PHP 文件缓存类,求大神们指导优化。

class Cache {

  //缓存目录
  protected static $dir = '../temp/cache/';
  /**
   * 设置缓存
   */
  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;
  }
}
Cache::set($key,$value,$time) //设置缓存
Cache::get($key)              //取得缓存
Cache::del($key)              //删除缓存
Cache::clear()                //清空缓存

练习所写 求大神们指导不合适的地方,还有没有可以优化的地方。

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!