Caching improves the page performance to a greater extent, especially if the page contains static content.
Codeigniter 4 provides caching methods with expiry which we can set in Controller.
Let’s say you have a Home.php controller with below function for the index page.
public function index() {
$expire_seconds = 100;
$this->cachePage($expire_seconds);
return view('welcome_message');
}
We can mention the number of seconds the page should be set in cache. CI4 detects the cache page and automatically fetches the page from cache , until it expires. The cache will be set again on the subsequent call after expiry. We can see the cache file set at the location “writable/cache/”, the file name will look similar to md5 hash.
The file is not deleted automatically on expiry, the file remains but CI4 does not read from the cache after expiry. In case we have to refresh the cache before expiry, we will have to manually remove the file from this location.
If we have to cache the url along with query string parameters, we can do the settings at app/Config/Cache.php file. We can set the variable $cacheQueryString to true or false based on the requirement. We can set the default expiry as well by modifying the $ttl variable value. The default is set to 60 seconds.
It is also possible to use redis or memcache server to set the cached pages. All the settings are available at app/Config/Cache.php file.