dir = $dir; } } /** * 设置缓存 * @param string $key * @param string $value * @param int $timeout * @return bool */ public function set($key, $value, $timeout = 10) { $this->createCacheDir(); $filename = $this->getFileName($key); if (is_array($value) || is_object($value)) { $value = json_encode($value); } $content = '' . PHP_EOL . $value; if (file_put_contents($filename, $content)) { return true; } return false; } /** * 获取缓存 * @param string $key * @param null $callable * @return bool|false|string */ public function get($key = null, $callable = null) { $filename = $this->getFileName($key); // 如果缓存文件存在 if (file_exists($filename)) { // 判断文件是否有效 if ($this->isTimeOut($key)) { // 返回缓存数据 return $this->getCacheContent($key); } } // 如果缓存不存在或缓存无效并且存在callable if (is_callable($callable)) { return $callable($this); } return false; } /** * 删除缓存 * @param string $key * @return bool */ public function remove($key = null) { $filename = $this->getFileName($key); if (file_exists($filename)) { @unlink($filename); } return true; } /** * 判断缓存是否存在/有效 * @param $key * @return bool */ public function exists($key) { return $this->isTimeOut($key); } /** * 获取文件缓存内容 * @param $key * @return false|string */ private function getCacheContent($key) { $filename = $this->getFileName($key); ob_start(); require $filename; $content = ob_get_contents(); ob_clean(); $jsonDecode = json_decode($content, true); if (is_null($jsonDecode)) { return $content; } return $jsonDecode; } /** * 判断缓存是否超时 * @param $key * @return bool */ private function isTimeOut($key) { $filename = $this->getFileName($key); if (file_exists($filename)) { ob_start(); require $filename; ob_clean(); $mtime = filemtime($filename); if ($timeout == 0) { return true; } elseif ((time() - $mtime >= $timeout)) { // 已超时,删除缓存 $this->remove($key); return false; } else { return true; } } return false; } /** * 获取缓存文件名称 * @param $key * @return string */ public function getFileName($key) { return $this->dir . $key . '.php'; } /** * 创建缓存目录 */ private function createCacheDir() { if (!is_dir($this->dir)) { mkdir($this->dir, 0777, true); } } }