Caching
A cache is temporary storage for ready results. If the list of popular articles takes a slow query, it is saved to the cache and served from there for the next few minutes without touching the database. In CakePHP this is the job of the Cache class.
Where it is configured
Storages are described in the Cache section of config/app.php. The default storage in a new project is files in the tmp/cache folder, so nothing has to be installed.
Writing and reading
// src/Controller/ArticlesController.php
use Cake\Cache\Cache;
public function stats(): void
{
$total = Cache::read('articles_total');
if ($total === null) {
$total = $this->Articles->find()->count();
Cache::write('articles_total', $total);
}
$this->set(compact('total'));
}read() returns the value for a key, or null when there is none. Then the value is computed and stored with write(). The first request of /articles/stats goes to the database and the following ones take the number from the cache.
Shorter: remember
$popular = Cache::remember('popular_articles', function () {
return $this->Articles->find()
->orderByDesc('views')
->limit(10)
->toArray();
});remember() does the same in one call: it returns the value from the cache, and when there is none it runs the function and stores the result. An array is put into the cache, toArray(), not the query itself.
Deleting
Cache::delete('popular_articles');A key is deleted when the data has changed, for example after an article is saved. The next request creates the value again.
Methods
| Method | What it does |
|---|---|
Cache::write($key, $value) | Stores a value |
Cache::read($key) | Reads a value or null |
Cache::remember($key, $callback) | Reads, or computes and stores |
Cache::delete($key) | Removes a value |
Cache::clear() | Clears the whole storage |
Lifetime
Add your own storage with a short lifetime to config/app.php:
// config/app.php
'Cache' => [
// ... the storages that were already in the file
'short' => [
'className' => \Cake\Cache\Engine\FileEngine::class,
'duration' => '+10 minutes',
'path' => CACHE,
],
],The storage name is passed as the last argument:
Cache::write('articles_total', $total, 'short');
$total = Cache::read('articles_total', 'short');After ten minutes the value expires and read() returns null again.
Other storages
| Class | Where it stores |
|---|---|
FileEngine | Files in tmp/cache |
RedisEngine | A Redis server |
MemcachedEngine | A Memcached server |
ArrayEngine | Memory for the duration of one request |
Code with Cache::read() and Cache::write() does not change when the storage is replaced.
Clearing from the console
bin/cake cache clear_allThe command clears all storages, including the internal cache of the framework itself.
Common mistake
An article was changed but the page shows old data: the cache has not expired yet. When you cache a result, decide right away when it is reset: by the duration lifetime or with a Cache::delete() call in the afterSave() method of the table class.