增加自动清除缓存特性;

This commit is contained in:
2022-02-12 17:02:45 +08:00
parent 90bbf61b6a
commit 7d8b948543
7 changed files with 260 additions and 154 deletions

View 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();
}
}
}
}