<?php
/**
* 文件缓存类
*/
class Infobird_Cache_File {
// 缓存文件基础目录
private $basePath;
// 目录层次级别
private $level;
private static $instance;
private function __construct($basePath, $level) {
$this->setBasePath($basePath);
$this->setLevel($level);
}
/**
* 设置缓存基础目录
* @param string $basePath
* @return void
* @throw Exception
*/
public function setBasePath($basePath) {
$basePath = rtrim(str_replace('\\', '/', realpath($basePath)), '/') . '/';
if (!file_exists($basePath)) {
throw new Exception('Directory does not exist.');
}
$this->basePath = $basePath;
}
/**
* 设置目录层次级别
* @param int $level
* @return void
* @throw Exception
*/
public function setLevel($level) {
$level = (int)$level;
if ($level <= 0 || $level > 5) {
throw new Exception('Directory level too deep, level: 1-5.');
}
$this->level = $level;
}
/**
* 获取缓存路径
* @param string $key
* @return string
* @throw Exception
*/
private function getCacheFilename($key) {
$id = md5($key);
$length = 2;
$path = $this->basePath;
$dir = $id;
for ($pos = 0, $max = $this->level * $length; $pos < $max; $pos += $length) {
$path .= substr($id, $pos, $length) . '/';
}
if (!file_exists($path)) {
if (!mkdir($path, '0777', true)) {
throw new Exception('Directory creation failed.' . $basePath);
}
}
return $path . $key;
}
/**
* 设置缓存数据
* @param string $key
* @param mixed $value
* @return bool
*
*/
public function set($key, $value) {
if (is_null($key) || !strlen($key)) {
return false;
}
$data = null;
if (is_array($value) || is_object($value)) {
$data = serialize($value);
}
$filename = $this->getCacheFilename($key);
file_put_contents($filename, $data);
return true;
}
/**
* 获取缓存数据
* @param string $key
* @return mixed
*/
public function get($key) {
if (is_null($key) || !strlen($key)) {
return false;
}
$filename = $this->getCacheFilename($key);
if (!file_exists($filename)) {
return false;
}
$fileData = file_get_contents($filename);
$data = @unserialize($fileData);
return $data;
}
/**
* 删除缓存数据
* @param string $key
* @return bool
*/
public function del($key) {
if (is_null($key) || !strlen($key)) {
return false;
}
$filename = $this->getCacheFilename($key);
if (file_exists($filename)) {
@unlink($filename);
}
return true;
}
/**
* 获取实例
* @param string $basePath 缓存目录
* @param string $level 目录层次级别
* @return object
*/
public static function getInstance($basePath, $level = 2) {
if (!self::$instance) {
$basePath = $basePath ? $basePath : PROJECT_ROOT . '/cache';
self::$instance = new Infobird_Cache_File($basePath, $level);
}
return self::$instance;
}
}