Cache database results or page output with CI4's Cache service using file, Redis, or APCu drivers.
Caching in CI4
// app/Config/Cache.php
public string $handler = "file"; // file, redis, memcached, predis, dummy
$cache = ConfigServices::cache();
// Store
$cache->save("key", $data, 3600); // TTL in seconds
// Retrieve
$data = $cache->get("key");
// Delete
$cache->delete("key");
$cache->clean(); // clear all
// Cache-or-fetch pattern
if (!$posts = $cache->get("all_posts")) {
$posts = model(PostModel::class)->findAll();
$cache->save("all_posts", $posts, 3600);
}
// Page caching (cache entire response)
class PostController extends BaseController {
public function index() {
$this->cachePage(300); // cache for 5 minutes
return view("posts/index", ["posts" => model(PostModel::class)->findAll()]);
}
}