完善缓存类

This commit is contained in:
TOP糯米 2024-07-18 16:50:00 +08:00
parent a9cb0a9161
commit 3c3298f2af
10 changed files with 148 additions and 51 deletions

View File

@ -17,6 +17,10 @@ return [
'open' => false, 'open' => false,
'prefix' => '', 'prefix' => '',
], ],
'cache' => [
'driver' => 'File',
'path' => './runtime/cache/',
],
'db' => [ 'db' => [
'driver' => 'Mysql', 'driver' => 'Mysql',
'host' => '127.0.0.1', 'host' => '127.0.0.1',
@ -36,11 +40,11 @@ return [
'engine' => 'Top', 'engine' => 'Top',
'tagLib' => [], 'tagLib' => [],
'ext' => 'html', 'ext' => 'html',
'dir' => APP_PATH . CURRENT_MODULE . '/view/', 'path' => APP_PATH . CURRENT_MODULE . '/view/',
'cacheDir' => './runtime/cache/application/' . CURRENT_MODULE . '/', 'cache_path' => './runtime/cache/application/' . CURRENT_MODULE . '/',
'compileDir' => './runtime/compile/application/' . CURRENT_MODULE . '/', 'compile_path' => './runtime/compile/application/' . CURRENT_MODULE . '/',
'left' => '<', 'left' => '<',
'right' => '>', 'right' => '>',
'cacheTime' => 5 'expire' => 5
], ],
]; ];

View File

@ -0,0 +1,90 @@
<?php
namespace top\library;
use top\library\cache\driver\FileCache;
use top\library\cache\driver\RedisCache;
use top\traits\Instance;
/**
* 缓存
* top\library\cache\Cache
*/
class Cache
{
use Instance;
/**
* 当前驱动
*
* @var top\library\cache\ifs\CacheIfs
*/
private $driver;
/**
* 构造函数
* Redis constructor.
*/
private function __construct()
{
$config = config('cache');
$type = strtolower($config['driver']);
switch ($type) {
case 'file':
$path = '';
if ($config['path']) {
$path = $config['path'];
}
$this->driver = FileCache::instance($path);
break;
case 'redis':
$this->driver = RedisCache::instance();
break;
default:
break;
}
}
/**
* 设置缓存
* @param string $key
* @param mixed $value
* @param int $expire
* @return bool
*/
public function set($key, $value, $expire = 0)
{
return $this->driver->set($key, $value, $expire);
}
/**
* 获取缓存
* @param string $key
* @return mixed
*/
public function get($key)
{
return $this->driver->get($key);
}
/**
* 移除缓存
* @param string $key
* @return bool
*/
public function remove($key)
{
return $this->driver->remove($key);
}
/**
* 判断是否存在
* @param string $key
* @return bool
*/
public function exists($key)
{
return $this->driver->exists($key);
}
}

View File

@ -7,10 +7,10 @@ use top\traits\Instance;
/** /**
* 文件缓存 * 文件缓存
* Class File * Class FileCache
* @package top\library\cache * @package top\library\cache
*/ */
class File implements CacheIfs class FileCache implements CacheIfs
{ {
use Instance; use Instance;
@ -30,18 +30,18 @@ class File implements CacheIfs
* 默认缓存位置 * 默认缓存位置
* @var string * @var string
*/ */
private $dir = './runtime/data/'; private $path = './runtime/data/';
/** /**
* 复写获取单一实例方法 * 复写获取单一实例方法
* @param string $dir * @param string $dir
* @return mixed * @return mixed
*/ */
public static function instance($dir = '') public static function instance($path = '')
{ {
$ident = md5($dir); $ident = md5($path);
if (!isset(self::$instance[$ident])) { if (!isset(self::$instance[$ident])) {
self::$instance[$ident] = new self($dir); self::$instance[$ident] = new self($path);
} }
return self::$instance[$ident]; return self::$instance[$ident];
} }
@ -51,10 +51,10 @@ class File implements CacheIfs
* File constructor. * File constructor.
* @param string $dir * @param string $dir
*/ */
private function __construct($dir = '') private function __construct($path = '')
{ {
if ($dir) { if ($path) {
$this->dir = $dir; $this->path = $path;
} }
} }
@ -62,16 +62,16 @@ class File implements CacheIfs
* 设置缓存 * 设置缓存
* @param string $key * @param string $key
* @param string $value * @param string $value
* @param int $timeout * @param int $expire
* @return bool * @return bool
*/ */
public function set($key, $value, $timeout = 10) public function set($key, $value, $expire = 10)
{ {
$this->createCacheDir(); $this->createCachePath();
$filename = $this->getFileName($key); $filename = $this->getFileName($key);
$cacheArray = [ $cacheArray = [
'create' => time(), 'create' => time(),
'time' => $timeout, 'expire' => $expire,
'value' => $value 'value' => $value
]; ];
$content = serialize($cacheArray); $content = serialize($cacheArray);
@ -123,7 +123,7 @@ class File implements CacheIfs
public function exists($key) public function exists($key)
{ {
$filename = $this->getFileName($key); $filename = $this->getFileName($key);
if (is_file($filename) && !$this->timeOut($key)) { if (is_file($filename) && !$this->expire($key)) {
return true; return true;
} }
return false; return false;
@ -141,20 +141,20 @@ class File implements CacheIfs
} }
/** /**
* 判断缓存是否超时 * 判断缓存是否过期
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
private function timeOut($key) private function expire($key)
{ {
$content = $this->readCacheFile($key); $content = $this->readCacheFile($key);
// 缓存文件存在,已读取到内容 // 缓存文件存在,已读取到内容
if (!empty($content)) { if (!empty($content)) {
$mtime = $content['create']; $mtime = $content['create'];
$timeout = $content['time']; $expire = $content['expire'];
if ($timeout == 0) { if ($expire == 0) {
return false; return false;
} elseif ((time() - $mtime >= $timeout)) { } elseif ((time() - $mtime >= $expire)) {
// 已超时,删除缓存 // 已超时,删除缓存
$this->remove($key); $this->remove($key);
return true; return true;
@ -195,16 +195,16 @@ class File implements CacheIfs
*/ */
public function getFileName($key) public function getFileName($key)
{ {
return $this->dir . $key . '.txt'; return $this->path . $key . '.txt';
} }
/** /**
* 创建缓存目录 * 创建缓存目录
*/ */
private function createCacheDir() private function createCachePath()
{ {
if (!is_dir($this->dir)) { if (!is_dir($this->path)) {
mkdir($this->dir, 0755, true); mkdir($this->path, 0755, true);
} }
} }

View File

@ -8,10 +8,10 @@ use top\traits\Instance;
/** /**
* Redis缓存 * Redis缓存
* Class Redis * Class RedisCache
* @package top\library\cache * @package top\library\cache
*/ */
class Redis implements CacheIfs class RedisCache implements CacheIfs
{ {
use Instance; use Instance;
@ -53,12 +53,12 @@ class Redis implements CacheIfs
* @param int $timeout * @param int $timeout
* @return bool * @return bool
*/ */
public function set($key, $value, $timeout = 10) public function set($key, $value, $expire = 10)
{ {
$data = ['value' => $value]; $data = ['value' => $value];
$value = serialize($data); $value = serialize($data);
$timeout = $timeout == 0 ? null : $timeout; $timeout = $expire == 0 ? null : $expire;
return $this->redis->set($key, $value, $timeout); return $this->redis->set($key, $value, $expire);
} }
/** /**

View File

@ -5,9 +5,12 @@ namespace top\library\cache\ifs;
interface CacheIfs interface CacheIfs
{ {
public function set($key, $value, $timeout = 0); public function set($key, $value, $expire = 0);
public function get($key, $callable = null); public function get($key, $callable = null);
public function remove($key); public function remove($key);
public function exists($key);
} }

View File

@ -18,14 +18,14 @@ class Smarty implements TemplateIfs
{ {
$this->config = \config('view'); $this->config = \config('view');
$this->smarty = new \Smarty(); $this->smarty = new \Smarty();
$this->smarty->setCacheDir($this->config['cacheDir']); $this->smarty->setCacheDir($this->config['cache_path']);
$this->smarty->setCompileDir($this->config['compileDir']); $this->smarty->setCompileDir($this->config['compile_path']);
return $this; return $this;
} }
public function cache($status) public function cache($status)
{ {
$time = (isset($this->config['cacheTime'])) ? $this->config['cacheTime'] : \Smarty::CACHING_LIFETIME_CURRENT; $time = (isset($this->config['expire'])) ? $this->config['expire'] : \Smarty::CACHING_LIFETIME_CURRENT;
$this->smarty->setCaching($time); $this->smarty->setCaching($time);
return true; return true;
} }
@ -35,7 +35,7 @@ class Smarty implements TemplateIfs
foreach ($params as $k => $v) { foreach ($params as $k => $v) {
$this->smarty->assign($k, $v); $this->smarty->assign($k, $v);
} }
$templateFile = $this->config['dir'] . $file . '.' . ltrim($this->config['ext'], '.'); $templateFile = $this->config['path'] . $file . '.' . ltrim($this->config['ext'], '.');
return $this->smarty->fetch($templateFile); return $this->smarty->fetch($templateFile);
} }
} }

View File

@ -2,7 +2,7 @@
namespace top\library\template\driver; namespace top\library\template\driver;
use top\library\cache\driver\File; use top\library\Cache;
use top\library\template\driver\engine\Engine; use top\library\template\driver\engine\Engine;
use top\library\template\ifs\TemplateIfs; use top\library\template\ifs\TemplateIfs;
use top\traits\Instance; use top\traits\Instance;
@ -41,10 +41,10 @@ class Top implements TemplateIfs
*/ */
private function compile($filename) private function compile($filename)
{ {
$compileFileName = $this->config['compileDir'] . md5($filename) . '.php'; $compileFileName = $this->config['compile_path'] . md5($filename) . '.php';
if (!file_exists($compileFileName) || DEBUG === true) { if (!file_exists($compileFileName) || DEBUG === true) {
if (!is_dir($this->config['compileDir'])) { if (!is_dir($this->config['compile_path'])) {
mkdir($this->config['compileDir'], 0755, true); mkdir($this->config['compile_path'], 0755, true);
} }
if (isset($this->config['tagLib']) && !empty($this->config['tagLib'])) { if (isset($this->config['tagLib']) && !empty($this->config['tagLib'])) {
foreach ($this->config['tagLib'] as $prefix => $className) { foreach ($this->config['tagLib'] as $prefix => $className) {
@ -76,7 +76,7 @@ class Top implements TemplateIfs
*/ */
private function cacheFile($filename, $params, $cacheTime) private function cacheFile($filename, $params, $cacheTime)
{ {
$cache = File::instance($this->config['cacheDir']); $cache = Cache::instance($this->config['cache_path']);
extract($params); extract($params);
// 获取文件内容 // 获取文件内容
ob_start(); ob_start();
@ -102,11 +102,11 @@ class Top implements TemplateIfs
*/ */
public function fetch($file, $params, $cache) public function fetch($file, $params, $cache)
{ {
$filename = $this->config['dir'] . $file . '.' . $this->config['ext']; $filename = $this->config['path'] . $file . '.' . $this->config['ext'];
if (file_exists($filename)) { if (file_exists($filename)) {
$filename = $this->compile($filename); $filename = $this->compile($filename);
if ($this->cache || $cache) { if ($this->cache || $cache) {
$cacheTime = $this->config['cacheTime']; $cacheTime = $this->config['expire'];
if (!is_bool($cache) || !is_bool($this->cache)) { if (!is_bool($cache) || !is_bool($this->cache)) {
if ($cache > 0) { if ($cache > 0) {
$cacheTime = $cache; $cacheTime = $cache;

View File

@ -27,11 +27,11 @@ class Twig implements TemplateIfs
public function fetch($file, $params, $cache) public function fetch($file, $params, $cache)
{ {
$baseViewDir = rtrim($this->config['dir'], '/') . '/'; $baseViewDir = rtrim($this->config['path'], '/') . '/';
$loader = new FilesystemLoader($baseViewDir); $loader = new FilesystemLoader($baseViewDir);
$loader->addPath($baseViewDir, 'base'); $loader->addPath($baseViewDir, 'base');
$template = new Environment($loader, [ $template = new Environment($loader, [
'cache' => rtrim($this->config['cacheDir'], '/') . '/', 'cache' => rtrim($this->config['cache_path'], '/') . '/',
'auto_reload' => true, 'auto_reload' => true,
'debug' => DEBUG 'debug' => DEBUG
]); ]);

View File

@ -72,7 +72,7 @@ class Engine
$blockPattern = '/' . $this->left . 'block\s+name[\s\S]*?=[\s\S]*?[\'"](.*?)[\'"][\s\S]*?' . $this->right; $blockPattern = '/' . $this->left . 'block\s+name[\s\S]*?=[\s\S]*?[\'"](.*?)[\'"][\s\S]*?' . $this->right;
$blockPattern .= '([\s\S]*?)' . $this->left . '\/block' . $this->right . '/is'; $blockPattern .= '([\s\S]*?)' . $this->left . '\/block' . $this->right . '/is';
// 获得被继承的模板内容 // 获得被继承的模板内容
$file = $this->config['dir'] . $matches[1] . '.' . ltrim($this->config['ext'], '.'); $file = $this->config['path'] . $matches[1] . '.' . ltrim($this->config['ext'], '.');
$extendFileContent = null; $extendFileContent = null;
if (file_exists($file)) { if (file_exists($file)) {
$extendFileContent = file_get_contents($file); $extendFileContent = file_get_contents($file);
@ -119,7 +119,7 @@ class Engine
$pattern = '/' . $this->left . 'include\s+file[\s\S]*?=[\s\S]*?[\'"](.*?)[\'"][\s\S]*?\/' . $this->right . '/is'; $pattern = '/' . $this->left . 'include\s+file[\s\S]*?=[\s\S]*?[\'"](.*?)[\'"][\s\S]*?\/' . $this->right . '/is';
$template = preg_replace_callback($pattern, function ($result) { $template = preg_replace_callback($pattern, function ($result) {
$string = null; $string = null;
$file = $this->config['dir'] . $result[1] . '.' . ltrim($this->config['ext'], '.'); $file = $this->config['path'] . $result[1] . '.' . ltrim($this->config['ext'], '.');
if (file_exists($file)) { if (file_exists($file)) {
$string = file_get_contents($file); $string = file_get_contents($file);
} }

View File

@ -2,7 +2,7 @@
namespace top\middleware; namespace top\middleware;
use top\library\cache\driver\File; use top\library\Cache;
use top\library\http\Request; use top\library\http\Request;
use top\library\http\Response; use top\library\http\Response;
use top\middleware\ifs\MiddlewareIfs; use top\middleware\ifs\MiddlewareIfs;
@ -21,8 +21,8 @@ class View implements MiddlewareIfs
if (!DEBUG) { if (!DEBUG) {
$ident = view_cache_ident(); $ident = view_cache_ident();
$config = \config('view'); $config = \config('view');
(!$config['cacheDir']) && $config['cacheDir'] = './runtime/cache/application/' . request()->module() . '/'; (!$config['cache_path']) && $config['cache_path'] = './runtime/cache/application/' . request()->module() . '/';
$cache = File::instance($config['cacheDir']); $cache = Cache::instance($config['cache_path']);
if ($cache->exists($ident)) return Response::instance()->send($cache->get($ident)); if ($cache->exists($ident)) return Response::instance()->send($cache->get($ident));
} }