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 secondscache('key')— read (returnsnullif 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:clearphp spark cache:info
Example
<?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.