Web Page Caching in CodeIgniter 4 Tutorial

Share this Article

CodeIgniter lets you cache your pages in order to achieve maximum performance.

CodeIgniter is quite fast, the amount of dynamic information what we need to display in pages will correlate directly to the server resources, memory, and processing cycles utilized, which affect page load speeds. By caching pages, since they are saved in their fully rendered state, we can achieve performance much closer to that of static web pages.

Inside this article we will see the concept of Web Page caching in CodeIgniter 4. Additionally we will discuss How can we clear web cache as well. This article is quite interesting to learn page caching in CodeIgniter.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Settings Environment Variables

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


How does Page Caching Works?

Caching can be enabled on a per-page basis, and you can set the length of time that a page should remain cached before being refreshed. When a page is loaded for the first time, the file will be cached using the currently configured cache engine.

On subsequent page loads, the cache file will be retrieved and sent to the requesting user’s browser. If it has expired, it will be deleted and refreshed before being sent to the browser.


Cache Configuration in Application

To configure cache – means where cache files will be stored what permission should be assigned to created cache files. All these settings we will do in Cache.php file at /app/Config.

public $file = [
     'storePath' => WRITEPATH . 'cache/',
     'mode' => 0640,
];

By default it will be stored with 0640 file permission and at /writable/cache folder.


Caching Information by PHP Spark

In codeigniter 4.x we have provided a command line interface through which we can manage CodeIgniter 4 application i.e by php spark

To manage cache also we have a php spark command.

In the above commands list we have two command –

  • cache:clear – To clear application caches
  • cache:info – To display application cache information.

Clear CodeIgniter 4 Application Cache

Open project in terminal and type this command.

$ php spark cache:clear

It will clear all cache from application which is at /writable/cache folder.

Display Application Cache Information

$ php spark cache:info

Application cache which will be stored inside /writable/cache folder will be displayed here inside this tabular format.


Caching a Web Page

To understand the page caching concept, let’s make a route, controller, it’s method and a view file.

Adding Route

Open Routes.php from /app/Config and add this route into it.

$routes->get("cache-this-page", "Site::index");

Create a View file

Create a view file with name site_index.php at /app/Views.

<h2>Welcome to Site Controller "index"</h2>

Create a Controller

$ php spark make:controller Site

It will creates a file with name Site.php at /app/Controllers

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class Site extends BaseController
{
	public function index()
	{
        $options = [
           "cache" => 60 // it is in seconds, means 60 seconds 
        ];
		return view("site_index", [], $options);
	}
}

Here we are caching the page view site_index for 60 seconds. It means the site_index page content will be fix for this given time slot.

When any user view this page, page will have the fixed content what it contains before caching. When we add any other contents into a cached view file, it will be reflect any more.

Web Page Caching Analysis

view(“template-file”, $data, $options)

When we set cache = 60 means the view file will be cached in application for 60 seconds. Whenever we load the web page again and again in between 60 seconds then page will not be rendered from /app/Views instead it will be loaded from cache folder i.e /writable/cache.


Alternative Option to Cache Web Page

We don’t have the single approach to do this by adding $options into view(). We have a method in CodeIgniter 4 which will do the same what we achieved above.

Let’s modify the same controller code by this method –

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class Site extends BaseController
{
	public function index()
	{
		// $options = [
		// 	"cache" => 60 // it is in seconds, means 60 seconds 
		// ];
		
		$this->cachePage(60); // 60 seconds

		return view("site_index");
	}
}

Deleting Application Caches

Caching multiple web pages some times not give the better presentation what we expect after doing a work effort over template files.

Templates render always from cache according to assigned time slots.

Page Cache will be removed from these ways –

  • Automatically pages will be removed from cache when the cache time expires for that page.
  • Manually delete page cache from /writable/cache folder.
  • Use Spark command php spark cache:clear

Using Service to display Cache Information

We have a CodeIgniter 4 service by the help of which we can display cache information. The same cache information we have displayed above using php spark cache:info.

Cache Service

We are using service inside a controller to display cache information.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class Site extends BaseController
{
	public function index()
	{
		$cache = \Config\Services::cache();
		echo "<pre>";
		print_r($cache->getCacheInfo());
	}
}

When we run this, here is the output of this method –

$cache = \Config\Services::cache();

print_r($cache->getCacheInfo());

OR

$cache = service("cache");

print_r($cache->getCacheInfo());

We hope this article helped you to learn Web Page Caching in CodeIgniter 4 in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

1 thought on “Web Page Caching in CodeIgniter 4 Tutorial”

Leave a Comment