mirror of
https://gitee.com/ulthon/ulthon_information.git
synced 2026-03-03 16:24:28 +08:00
增加自动清除缓存特性;
This commit is contained in:
65
app/common/traits/AutoClearCache.php
Normal file
65
app/common/traits/AutoClearCache.php
Normal file
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\traits;
|
||||
|
||||
use think\facade\Cache;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
trait AutoClearCache
|
||||
{
|
||||
|
||||
/**
|
||||
* 自动清除的缓存值
|
||||
*
|
||||
* [
|
||||
* 'name'=>'',
|
||||
* 'type'=>'', // tag/key
|
||||
* 'field'=>'' // 为空则不做拼接
|
||||
* ]
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $autoClearCache = [];
|
||||
|
||||
public static function onAfterWrite($model)
|
||||
{
|
||||
static::autoRemoveCache($model);
|
||||
}
|
||||
public static function onAfterDelete($model)
|
||||
{
|
||||
static::autoRemoveCache($model);
|
||||
}
|
||||
public static function onAfterRestore($model)
|
||||
{
|
||||
static::autoRemoveCache($model);
|
||||
}
|
||||
public static function autoRemoveCache($model)
|
||||
{
|
||||
|
||||
foreach (static::$autoClearCache as $cache_item) {
|
||||
$type = $cache_item['type'] ?: 'key';
|
||||
|
||||
$field = $cache_item['field'] ?: '';
|
||||
|
||||
$cache_key = $cache_item['name'] ?: '';
|
||||
|
||||
if (empty($cache_key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!empty($field)) {
|
||||
if (!is_null($model->$field)) {
|
||||
$cache_key = $cache_key . '_' . $model->$field;
|
||||
}
|
||||
}
|
||||
|
||||
if ($type == 'key') {
|
||||
Cache::delete($type);
|
||||
} else {
|
||||
Cache::tag($cache_key)->clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user