agyanadda@gmail.com

CodeIgniter 4 Caching

APIs and Advanced Topics 1 min read Updated Dec 3, 2026 Topic 26 of 30

Caching saves the result of slow work so later requests are fast.

Cache handlers

Configure in app/Config/Cache.php ($handler). The default file handler stores data in writable/cache. Others include redis, memcached, predis and wincache. A backup handler is used if the main one is unavailable.

Data caching

  • cache()->save('key', $data, 600) — store for 600 seconds
  • cache('key') — read (returns null if missing)
  • cache()->delete('key'), cache()->clean()
  • cache()->remember('key', 600, fn () => ...) — return the cached value, or run the function, save and return it

Clear the cache when data changes

After saving or deleting a post, delete the related keys so visitors do not see old data.

Page caching

In a controller method, $this->cachePage(300); stores the whole page output for 300 seconds. It is great for public pages that are the same for everyone — never use it on pages showing personal data.

Commands

  • php spark cache:clear
  • php spark cache:info

Example

Example — Cache homepage data PHP
<?php
public function index()
{
    $posts = cache()->remember('home_latest_posts', 1800, static function () {
        return model('PostModel')
            ->where('status', 'published')
            ->orderBy('id', 'DESC')
            ->findAll(10);
    });

    $categories = cache()->remember('all_categories', 86400, static fn () => model('CategoryModel')->findAll());

    return view('home', compact('posts', 'categories'));
}

// After saving a post (in the admin controller):
cache()->delete('home_latest_posts');

The first visitor runs the queries; for the next 30 minutes (posts) and 24 hours (categories) the data comes from writable/cache. Saving a post clears the posts cache, so changes show at once.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method returns cached data or creates it with a function?

Exercise 2 True / False

Full page caching is safe for pages that show each user's personal data.

Exercise 3 Fill in the Blank

Clear the cache from the terminal with php spark cache:___

Frequently Asked Questions

In writable/cache. That folder must be writable by the web server. Deleting its files (except index.html) or running php spark cache:clear empties the cache.