前言:一般分类基本不会动,所以我们在分类当中加入缓存
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.生成缓存的时候,会生成缓存文件,那么我们就需要删除项目缓存文件,当然也可以让其自动更新:
https://www.kancloud.cn/manual/thinkphp5_1/354019
/***
* 执行清除
*/
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;
}
}
}