Page Caching
Caching reduces work for repeat visitors. CodeIgniter can cache a whole rendered page for a number of seconds, and it can also cache individual data values through the cache service.
Cache a controller page
public function index()
{
$this->cachePage(300); // 5 minutes
return view('catalog/index', ['products' => $this->products()]);
}
Page caching is best for public, identical responses. Do not cache pages that change per user, contain CSRF tokens, or show private data.
Cache data
$cache = service('cache');
$stats = $cache->get('home_stats');
if ($stats === null) {
$stats = $this->calculateStats();
$cache->save('home_stats', $stats, 600);
}
Clear and invalidate
$cache->delete('home_stats');
// Or remove everything after a deployment:
cache()->clean();
Choosing a handler
File caching is simple and works on most hosts. Redis or Memcached is a better choice when multiple servers must share cached values. Set the handler in app/Config/Cache.php or through .env.
Guidelines
- Cache only data that is expensive to produce and safe to reuse.
- Include a version or key prefix so a deployment does not serve stale structures.
- Invalidate when the underlying records change.
- Avoid very long lifetimes for prices, stock, or availability.
- Test the cache-disabled path as well as the cached path.
Back to course overview · Previous: Common Functions · Next: Page Redirection