thinkPHP5网站后台添加一键清除缓存功能
侧边栏壁纸
  • 累计撰写 114 篇文章
  • 累计收到 21 条评论

thinkPHP5网站后台添加一键清除缓存功能

SanLiLin
2019-03-13 / 0 评论 / 512 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年01月08日,已超过802天没有更新,若内容或图片失效,请留言反馈。

前言

thinkPHP的缓存功能对于网站运行来说是比不可少的,但是在有些时候,特别是在做开发的时候,缓存实在是令人头疼,这边文章分享下tp5通过ajax提交达到一键清除网站缓存的功能

使用方法

后端PHP中

  1. 在公共文件common.php中添加公共方法

    if (!function_exists('delete_dir_file')) {
    
        /**
         * 循环删除目录和文件
         * @param string $dir_name
         * @return bool
         */
        function delete_dir_file($dir_name) {
            $result = false;
            if(is_dir($dir_name)){
                if ($handle = opendir($dir_name)) {
                    while (false !== ($item = readdir($handle))) {
                        if ($item != '.' && $item != '..') {
                            if (is_dir($dir_name . DS . $item)) {
                                delete_dir_file($dir_name . DS . $item);
                            } else {
                                unlink($dir_name . DS . $item);
                            }
                        }
                    }
                    closedir($handle);
                    if (rmdir($dir_name)) {
                        $result = true;
                    }
                }
            }
         
            return $result;
        }
    }
  2. controller(控制器)中添加

    /**
     * 清除缓存
     */
    public function clear() {
        if (delete_dir_file(CACHE_PATH) || delete_dir_file(TEMP_PATH)) {
            $this->success('清除缓存成功!');
        } else {
            $this->error('清除缓存失败!');
        }
    }
  3. JavaScript中添加
<script type="text/javascript">
//清除缓存
function clearPhp(obj) {
    var url=obj.getAttribute('data-GetUrl');
    //询问框
    layer.confirm('你确定要清除缓存吗?', {icon: 3, title:'提示'},
    function(){
        $.get(url,function(info){
            if(info.code === 1){
                setTimeout(function () {location.href = info.url;}, 1000);
            }
            layer.msg(info.msg,{icon:1});
        });
    },
    function(){});
}
</script>
  1. html页面中,因为需要在任何页面都能快速清除缓存,所以我把调用代码写在了公共文件中

    <a href="javascript:void(0);" class="list-group-item cache" onclick="clearPhp(this)" data-GetUrl="{:url('admin/clear')}">
        <div class="media">
            <div class="media-img" style="color: #333;"><i class="fa fa-bolt"></i></div>
            <div class="media-body">
                <div class="font-strong"></div>清除所有缓存<small class="text-muted float-right">删除所有 temp+cache</small>
            </div>
        </div>
    </a>
    这样下来就能达到一键清除系统缓存的目的了
0

评论 (0)

取消