thinkphp 做整站缓存自定义模型方法

本文介绍如何在ThinkPHP框架中通过封装一个基础模型,实现整站缓存功能。各业务模型可继承此基础模型,利用自定义方法进行缓存操作,提升网站性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

thinkphp 做整站缓存自定义模型方法

封装一个基础模型,其他模型继承,调用模型的方法

namespace app\common\model;


use think\facade\Cache;
use think\Model;

class BaseModel extends Model
{
    private $_cache_list_tag = '_xc2020_cache_list_tag_';// 列表缓存标签
    private $_cache_detail_tag = '_xc2020_cache_detail_tag_';// 详细缓存标签
    private $_cache_key = '_xc2020_cache_key_';// 缓存后缀

    /**
     * 执行添加
     * @param array $data 数据
     * @param bool 是否启用缓存
     * @param string $tag 缓存标签
     * @return bool
     */
    public function execInsert($data, $cache = false, $tag = '')
    {
        $data['create_time'] = time();
        $res                 = self::create($data);
        if (!$res) {
            return false;
        }
        if ($cache) {
            $this->deleteListCache($tag);
        }
        return $res[self::getPk()];
    }

    /**
     * @param int $pk 主键值
     * @param bool 是否启用缓存
     * @param string $tag 缓存标签
     * @return bool
     */
    public function execDelete($pk, $cache = false, $tag = '')
    {
        $res = self::destroy($pk);
        if (!$res) {
            return false;
        }
        if ($cache) {
            $this->deleteListCache($tag);
            $this->deleteDetailCache($pk);
        }
        return $res;
    }

    /**
     * @param int $pk 主键值
     * @param string $sql 原生sql
     * @param bool 是否启用缓存
     * @param string $tag 缓存标签
     * @return bool
     */
    public function execDelete2($pk,$query, $cache = false, $tag = '')
    {
        $res = self::query($query);
        if ($res===false) {
            return false;
        }
        if ($cache) {
            $this->deleteLis
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值