如果有些資料我們需要暫存,特別是從資料庫來的資料,這樣可以加快網站開啟速度也能降低伺服器的資源使用,在 CodeIgniter 4 我們就可以使用其提供的 Caching Driver。
像這樣就可以建立 Cache:
if (! $foo = cache('foo')) {
echo 'Saving to the cache!
';
$foo = 'foobarbaz!';
// Save into the cache for 5 minutes
cache()->save('foo', $foo, 300);
}
echo $foo;
如果是在 Model 裡會是像這樣:
if (!$data = cache($cache)) {
$storeModel = model(StoreModel::class);
$data = $storeModel->findAll();
cache()->save($cache, $data, 300);
}
return $data;
這樣如果有 Cache 就不會進資料庫了。
透過 instance 取得資料。
$cache = \Config\Services::cache();
$foo = $cache->get('foo');
如果要刪除的話可以使用 delete
$cache->delete('cache_item_id');
以上為 cache 基本用法,更多內容也可以參考官方文件說明。