Thinkphpのキャッシュの使用は、システムパフォーマンスを効果的に改善し、データベース操作とメモリコストを節約できます。
簡単な例:
<?php
use think\Cache;
if (Cache::has('user_data')) {
$users = Cache::get('user_data')
} else {
$users = User::where('status', 1)->select();
// 缓存用户数据5分钟
Cache::set('user_data', $users, 300);
}
上記のコードは、次のように簡略化することもできます。
<?php
use think\Cache;
$users = Cache::remember('user_data', function(){
return User::where('status', 1)->select();
},300);
問題は、上記のキャッシュ時間が5分であるということです。この5分以内にユーザーユーザーテーブルを追加、変更、削除すると、キャッシュが変更されておらず、Webサイトが最も信頼できるデータを取得できないことがわかります。時間。私たちは何をすべきか?
解決:
追加、変更、削除などの操作を実行した後、次のようにCache :: clear()を呼び出します。
<?php
use think\Cache;
public function add(){
try{
User::create([
'name' => "tom",
'age' => 18
]);
} catch (\Exception $e) {
$this->error('添加失败');
}
//清理缓存
Cache::clear();
$this->success('添加成功');
}
補足:キャッシュ、テンプレートキャッシュ、ログキャッシュをクリアする方法
namespace app\cache\controller;
use think\Controller;
use think\Cache;
//清除模版缓存不删除cache目录;
public function clear_sys_cache()
{
Cache::clear();
$this->success('清除成功', 'Index/index');
}
//清除模版缓存但不删除temp目录;
public function clear_temp_ahce()
{
$path = glob(TEMP_PATH . '*.php');
array_map('unlink', $path);
//rmdir(TEMP_PATH .'temp/');//删除temp目录
$this->success('清除成功', 'Index/index');
}
//清除日志缓存并删出log空目录;
public function clear_log_chache()
{
$path = glob(LOG_PATH . '*');
foreach ($path as $item) {
//dump(glob($item .DS. '*.log'));
array_map('unlink', glob($item . DS . '*.log'));
rmdir($item);
}
$this->success('清除成功', 'Index/index');
}