自己练手写的 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()                //清空缓存

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

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 2
(= ̄ω ̄=)··· 暂无内容!

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