tp5缓存在html怎么用,tp5.1缓存Cache的使用
前言:一般分類基本不會動,所以我們在分類當中加入緩存
1.控制器use
use think\facade\Cache;
2.存取緩存
public function index()
{
if (Cache::get('category')) { //判斷是否存在
$categories = Cache::get('category'); //存在就讀緩存
} else {
$categories = Categories::all_categories();
Cache::set('category', $categories); //不存在就設置緩存
}
$this->assign(compact('categories'));
return $this->fetch();
}
3. 刪除緩存,當我們新增或者編輯的時候,數據發生了改變,那么我們先刪除緩存然后再去設置新的緩存
Cache::rm('category');
例如:這里的allowfield是希望指定某些字段寫入
public function update(Request $request)
{
$categories = new Categories();
$categories->allowField(['name', 'photo_id'])->save($_POST, ['id' => $request->id]);
Cache::rm('category');
}
4.生成緩存的時候,會生成緩存文件,那么我們就需要刪除項目緩存文件,當然也可以讓其自動更新:
/***
* 執行清除
*/
public function cache()
{
$path = ROOT_PATH . '/runtime/temp';
delDirAndFile($path); //這里是一個助手函數
$this->success('清除模板緩存成功', 'Index/index');
}
助手函數common.php中
/**
* 刪除目錄及目錄下所有文件或刪除指定文件
* @param str $path 待刪除目錄路徑
* @param int $delDir 是否刪除目錄,1或true刪除目錄,0或false則只刪除文件保留目錄(包含子目錄)
* @return bool 返回刪除狀態
*/
function delDirAndFile($path, $delDir = FALSE)
{
$handle = opendir($path);
if ($handle) {
while (false !== ($item = readdir($handle))) {
if ($item != "." && $item != "..")
is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
}
closedir($handle);
if ($delDir)
return rmdir($path);
} else {
if (file_exists($path)) {
return unlink($path);
} else {
return FALSE;
}
}
}
總結
以上是生活随笔為你收集整理的tp5缓存在html怎么用,tp5.1缓存Cache的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 南昌理工学院的计算机科学与技术专业怎么样
- 下一篇: 吉林财经计算机学院怎么样,2019年9月