ThinkPHP5.1 清除緩存


ThinkPHP5.1 清除緩存

在基類控制器里,寫上clear()方法,到時候用於調用,在也不是JSalert('清除緩存了')
當然,5.1取消了CACHE_PATH TEMP_PATH常量,所以要定義這些緩存目錄,還需引入use think\facade\Env

// 我是直接按照文檔,設置了2個變量來存儲緩存目錄,當然還可以在配置文件中進行配置,然后通過config獲取
public function clear(){
	$CACHE_PATH = Env::get('runtime_path') . 'cache/';
	$TEMP_PATH = Env::get('runtime_path'). 'temp/';
    if (delete_dir_file($CACHE_PATH) && delete_dir_file($TEMP_PATH)) {
        return json(["code"=>1,"msg"=>"清除緩存成功"]);
    } else {
        return json(["code"=>0,"msg"=>"清除緩存失敗"]);
    }
}

這個時候發現delete_dir_file()函數未定義,我們去公共函數里進行定義並寫出來:
由於5.1 沒有DS常量了,所以選用DIRECTORY_SEPARATOR來代替

common.php:

/**
 * 循環刪除目錄和文件
 * @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 . DIRECTORY_SEPARATOR. $item)) {
                        delete_dir_file($dir_name . DIRECTORY_SEPARATOR. $item);
                    } else {
                        unlink($dir_name . DIRECTORY_SEPARATOR. $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }
    return $result;
}

第二種方法

public function delCache() {
	if (Dir::del(Env::get('runtime_path').'cache/') {
		$data = ['status' => 1, 'info' => '緩存刪除成功'];
	} else {
		$data = ['status' => 0, 'info' => '緩存刪除失敗];
	}
	return json($data);
}

這個需要一個Dir類

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: superman <953369865@qq.com>
// +----------------------------------------------------------------------
namespace Org\Util;
use Think\Db;
final class Dir
{

    /**
     * @param string $dir_name 目錄名
     * @return mixed|string
     */
    static public function dirPath($dir_name)
    {
        $dirname = str_ireplace("\\", "/", $dir_name);
        return substr($dirname, "-1") == "/" ? $dirname : $dirname . "/";
    }

    /**
     * 獲得擴展名
     * @param string $file 文件名
     * @return string
     */
    static public function getExt($file)
    {
        return strtolower(substr(strrchr($file, "."), 1));
    }

    /**
     * 遍歷目錄內容
     * @param string $dirName 目錄名
     * @param string $exts 讀取的文件擴展名
     * @param int $son 是否顯示子目錄
     * @param array $list
     * @return array
     */
    static public function tree($dirName = null, $exts = '', $son = 0, $list = array())
    {
        if (is_null($dirName)) $dirName = '.';
        $dirPath = self::dirPath($dirName);
        static $id = 0;
        if (is_array($exts))
            $exts = implode("|", $exts);
        foreach (glob($dirPath . '*') as $v) {
            $id++;
            if (is_dir($v) || !$exts || preg_match("/\.($exts)/i", $v)) {
                $list [$id] ['type'] = filetype($v);
                $list [$id] ['filename'] = basename($v);
                $path = str_replace("\\", "/", realpath($v)) . (is_dir($v) ? '/' : '');
                $list [$id] ['path']=$path;
                $list [$id] ['spath']=ltrim(str_replace(dirname($_SERVER['SCRIPT_FILENAME']),'',$path),'/');
                $list [$id] ['filemtime'] = filemtime($v);
                $list [$id] ['fileatime'] = fileatime($v);
                $list [$id] ['size'] = is_file($v) ? filesize($v) : self::get_dir_size($v);
                $list [$id] ['iswrite'] = is_writeable($v) ? 1 : 0;
                $list [$id] ['isread'] = is_readable($v) ? 1 : 0;
            }
            if ($son) {
                if (is_dir($v)) {
                    $list = self::tree($v, $exts, $son = 1, $list);
                }
            }
        }
        return $list;
    }

    static public function get_dir_size($f)
    {
        $s = 0;
        foreach (glob($f . '/*') as $v) {
            $s += is_file($v) ? filesize($v) : self::get_dir_size($v);
        }
        return $s;
    }

    /**
     * 只顯示目錄樹
     * @param null $dirName 目錄名
     * @param int $son
     * @param int $pid 父目錄ID
     * @param array $dirs 目錄列表
     * @return array
     */
    static public function treeDir($dirName = null, $son = 0, $pid = 0, $dirs = array())
    {
        if (!$dirName) $dirName = '.';
        static $id = 0;
        $dirPath = self::dirPath($dirName);
        foreach (glob($dirPath . "*") as $v) {
            if (is_dir($v)) {
                $id++;
                $dirs [$id] = array("id" => $id, 'pid' => $pid, "dirname" => basename($v), "dirpath" => $v);
                if ($son) {
                    $dirs = self::treeDir($v, $son, $id, $dirs);
                }
            }
        }
        return $dirs;
    }

    /**
     * 刪除目錄及文件,支持多層刪除目錄
     * @param string $dirName 目錄名
     * @return bool
     */
    static public function del($dirName)
    {
        if (is_file($dirName)) {
            unlink($dirName);
            return true;
        }
        $dirPath = self::dirPath($dirName);
        if (!is_dir($dirPath)) return true;
        foreach (glob($dirPath . "*") as $v) {
            is_dir($v) ? self::del($v) : unlink($v);
        }
        return @rmdir($dirName);
    }

    /**
     * 批量創建目錄
     * @param $dirName 目錄名數組
     * @param int $auth 權限
     * @return bool
     */
    static public function create($dirName, $auth = 0755)
    {
        $dirPath = self::dirPath($dirName);
        if (is_dir($dirPath))
            return true;
        $dirs = explode('/', $dirPath);
        $dir = '';
        foreach ($dirs as $v) {
            $dir .= $v . '/';
            if (is_dir($dir))
                continue;
            mkdir($dir, $auth);
        }
        return is_dir($dirPath);
    }

    /**
     * 復制目錄
     * @param string $olddir 原目錄
     * @param string $newdir 目標目錄
     * @param bool $strip_space 去空白去注釋
     * @return bool
     */
    static public function copy($olddir, $newdir, $strip_space = false)
    {
        $olddir = self::dirPath($olddir);
        $newdir = self::dirPath($newdir);
        if (!is_dir($olddir))
            error("復制失敗:" . $olddir . "目錄不存在");
        if (!is_dir($newdir))
            self::create($newdir);
        foreach (glob($olddir . '*') as $v) {
            $to = $newdir . basename($v);
            if (is_file($to))
                continue;
            if (is_dir($v)) {
                self::copy($v, $to, $strip_space);
            } else {
                if ($strip_space) {
                    $data = file_get_contents($v);
                    file_put_contents($to, strip_space($data));
                } else {
                    copy($v, $to);
                }
                chmod($to, "0777");
            }
        }
        return true;
    }

    /**
     * 目錄下創建安全文件
     * @param $dirName 操作目錄
     * @param bool $recursive 為true會遞歸的對子目錄也創建安全文件
     */
    static public function safeFile($dirName, $recursive = false)
    {
        $file = LIB_PATH . '/index.html';
        if (!is_dir($dirName)) {
            return;
        }
        $dirPath = self::dirPath($dirName);
        /**
         * 創建安全文件
         */
        if (!is_file($dirPath . 'index.html')) {
            copy($file, $dirPath . 'index.html');
        }
        /**
         * 操作子目錄
         */
        if ($recursive) {
            foreach (glob($dirPath . "*") as $d) {
                is_dir($d) and self::safeFile($d);
            }
        }
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM