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