<?php namespace Phpcmf\Library;
class Cache {
private $file_dir;
public function __construct(...$params) {
$this->file_dir = WRITEPATH.'data/'; }
private function parse_cache_file($file_name, $cache_dir = null) {
return ($cache_dir ? WRITEPATH.$cache_dir.'/' : $this->file_dir).$file_name.'.cache';
}
public function init_file($dir) {
$this->file_dir = WRITEPATH.trim($dir, '/').'/'; return $this;
}
public function set_file($key, $value, $cache_dir = null) {
if (!$key) {
return false;
}
$cache_file = self::parse_cache_file($key, $cache_dir); $value = dr_array2string($value);
$cache_dir = ($cache_dir ? WRITEPATH.$cache_dir.'/' : $this->file_dir);
!is_dir($cache_dir) ? dr_mkdirs($cache_dir, 0777) : (!is_writeable($cache_dir) && @chmod($cache_dir, 0777));
function_exists('opcache_reset') && opcache_reset();
$rt = @file_put_contents($cache_file, $value, LOCK_EX);
if ($rt === false) {
log_message('error', '缓存文件['.$cache_file.']无法写入');
}
return $rt ? true : false;
}
public function get_file($key, $cache_dir = null) {
if (!$key) {
return false;
}
$cache_file = self::parse_cache_file($key, $cache_dir);
return is_file($cache_file) ? @json_decode(@file_get_contents($cache_file), true) : false;
}
public function del_file($key, $cache_dir = null) {
if (!$key) {
return true;
}
$cache_file = self::parse_cache_file($key, $cache_dir);
return is_file($cache_file) ? @unlink($cache_file) : true;
}
public function del_all($dir = 'data') {
!$dir && $dir = 'data';
$path = WRITEPATH.$dir.'/';
dr_dir_delete($path);
return ;
}
public function init() {
return cache();
}
public function set_data($name, $value, $time = 3600) {
function_exists('opcache_reset') && opcache_reset();
$time && self::init()->save(md5('cache-'.SITE_ID.'-'.$name), $value, $time);
return $value;
}
public function get_data($name) {
return self::init()->get(md5('cache-'.SITE_ID.'-'.$name));
}
public function get() {
$param = func_get_args();
if (!$param) {
return null;
}
$name = strtolower(array_shift($param));
$result = $this->get_data($name);
if (!$result) {
$result = self::get_file($name);
if (!$result) {
return null;
}
$this->set_data($name, $result, 3600);
}
if (!$param) {
return $result;
}
$var = '';
foreach ($param as $v) {
$var.= '[\''.dr_safe_replace($v).'\']';
}
$return = null;
@eval('$return = $result'.$var.';');
return $return;
}
public function clear($name) {
$this->init()->delete('cache-'.SITE_ID.'-'.$name);
$this->init()->delete(md5('cache-'.SITE_ID.'-'.$name));
function_exists('opcache_reset') && opcache_reset();
}
}