此代码包含了缓存的存储,删除,编辑,以及设置缓存时间
此缓存机制主要核心内容是用 file_put_contents 和 file_get_contents 方法实现,小伙伴可以拿来直接用,也可以分析下代码,如果有什么不足欢迎大家前来讨论
粘贴代码直接可用
class File{ public $options = [ "dir" => "", "expire" => "", 'data_compress' => false, 'serialize' => ['easydev【{$date}】:'] ]; public function __construct($dir = 'runtime', int $expire = null, $data_compress = false) { $this->options['dir'] = __DIR__ . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR; $this->options['expire'] = is_null($expire) ? 0 : $expire; $this->options['data_compress'] = $data_compress; } public function set($field, $data, $expire = null) { $filename = $this->options['dir'] . self::getCacheField($field) . '.php'; $expire = $expire??$this->options['expire']; $dir = dirname($filename); if (!is_dir($dir)) mkdir($dir, 0755, true); $data = serialize($data); if ($this->options['data_compress'] && function_exists('gzcompress')) { //数据压缩 $data = gzcompress($data, 3); } $data = " . sprintf('%012d', $expire) . "\n exit();?>\n" . $data; $result = file_put_contents($filename, $data); if ($result) { clearstatcache(); } return $this; } public function get($field) { $filename = $this->options['dir'] . self::getCacheField($field) . '.php'; if(!file_exists($filename)) return false; $content = file_get_contents($filename); if (false !== $content) { $expire = (int)substr($content, 8, 12); if (0 != $expire && time() > filemtime($filename) + $expire) { unlink($filename); return false; } $content = substr($content, 32); if ($this->options['data_compress'] && function_exists('gzcompress')) { $content = gzuncompress($content); } return unserialize($content); } else { return false; } } public function delete($field){ $filename = $this->options['dir'] . self::getCacheField($field) . '.php'; if(!file_exists($filename)) return false; unlink($filename);return true; } public function has($field){ return self::get($field); } public function clear() { $files = (array)glob($this->options['dir'] . DIRECTORY_SEPARATOR . '*'); foreach ($files as $path) { if (is_dir($path)) { $matches = glob($path . DIRECTORY_SEPARATOR . '*.php'); if (is_array($matches)) { array_map('unlink', $matches); } rmdir($path); } else { unlink($path); } } return true; } public function getCacheField($name) { $name = hash('md5', $name); $name = substr($name, 0, 2) . DIRECTORY_SEPARATOR . substr($name, 2); return $name; }}
来源地址:https://blog.csdn.net/weixin_39687736/article/details/131932651