mirror of
https://gitee.com/ulthon/ulthon_information.git
synced 2026-03-03 16:24:28 +08:00
69 lines
1.4 KiB
PHP
69 lines
1.4 KiB
PHP
<?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->getAttr($field);
|
|
}
|
|
}
|
|
|
|
if ($type == 'key') {
|
|
Cache::delete($cache_key);
|
|
} else {
|
|
Cache::tag($cache_key)->clear();
|
|
}
|
|
}
|
|
}
|
|
}
|