Caching
A cache is a temporary store of ready results. If the list of popular posts takes a heavy query, it can be computed once, kept for a few minutes and served ready-made all that time. The page opens faster and the database rests. You work with the cache through the cache() function; by default the data lives in files in the writable/cache folder.
Writing and reading
// app/Controllers/Home.php
public function index(): string
{
$time = cache()->get('saved_time');
if ($time === null) {
$time = date('H:i:s');
cache()->save('saved_time', $time, 60);
}
return "Time in the cache: $time";
}Open the home page and reload it several times: the time does not change because it comes from the cache. After 60 seconds the value expires, get() returns null and a new time is written to the cache. The third argument of save() is the lifetime in seconds.
The remember method
The remember() method combines the "is the value there" check with saving:
// app/Controllers/Posts.php
public function popular(): string
{
$posts = cache()->remember('popular_posts', 600, static function () {
return model(PostModel::class)
->where('status', 1)
->orderBy('id', 'DESC')
->findAll(5);
});
return view('posts/index', ['posts' => $posts]);
}If the value is in the cache, it is returned at once. If not, the function runs and its result is kept for ten minutes. The database query runs once in ten minutes instead of on every page view.
Clearing the cache
When the data changes, the stale value is removed — usually right after a record is saved:
model(PostModel::class)->insert($data);
cache()->delete('popular_posts');The next visitor gets a fresh list. The php spark cache:clear command clears the whole cache.
Cache methods
| Call | What it does |
|---|---|
cache()->save('key', $value, 300) | Saves a value for 300 seconds |
cache()->get('key') | Returns the value or null |
cache('key') | The short form of reading |
cache()->remember('key', 300, $callback) | Reads, or computes and saves |
cache()->delete('key') | Removes a value |
cache()->clean() | Removes everything |
Use letters, digits and underscores in keys: curly and round brackets, the slash, the colon and the @ sign are forbidden.
Caching a whole page
A page that is the same for every visitor can be saved as a whole:
public function about(): string
{
$this->cachePage(3600);
return view('pages/about');
}For an hour CodeIgniter serves the ready HTML and does not call the controller at all.
Settings
The storage is chosen in app/Config/Cache.php with the $handler property. The file value suits a single server; redis and memcached are faster and needed when there are several servers.
Common mistake
Pages that depend on the visitor must not be cached as a whole: those with a user name, a cart, a form with a CSRF token. The first person to open the page ends up in the cache, and everyone else sees their data. For such pages cache only shared data through remember(), not the whole page.