<?php
namespace Lib;
class Cache{
public static $options = [
'expire' => 3600,
'path' => CACHE_PATH,
];
/**
* 初始化
*
@param array $options
*/
public function init($options = []){
self::$options = array_merge(self::$options, $options);
is_dir(self::$options['path']) or mkdir(self::$options['path'], 0755, true);
}
/**
* 设置缓存
*
@param $key
*
@param $val
*
@param array $options
*
@return bool
*/
public static function Set($key, $val, $options = []){
self::init($options);
$filename = self::getCacheFilename($key);
$data = sprintf('%012d', self::$options['expire']) . serialize($val);
if(file_put_contents($filename, $data)){ return true; }
return false;
}
/**
* 获取缓存
*
@param $key
*
@param $options
*
@return bool
*/
public static function Get($key, $options = []){
self::init($options);
$filename = self::getCacheFilename($key);
if(file_exists($filename)){
$data = file_get_contents($filename);
$expire = (int)substr($data, 0, 12);
if($expire !== 0) {
if (time() > ($expire + (int)filemtime($filename))) {
unlink($filename); return false;
}
}
return unserialize(substr($data, 12));
}
return false;
}
/**
* 获取缓存文件名
*
@param $key
*
@return string
*/
public static function getCacheFilename($key){
return self::$options['path'] . md5($key) . CACHE_PREFIX;
}
}