In this post, I will show you how easy it is to setup maintenance mode in CodeIgniter using CI’s hooks. while updating your web application its always better to show meaningful maintenance message to the end users, instead of showing errors.
We gonna use CIs hooks to set up the maintenance page. Using hooks you can extend the Framework Core. CodeIgniter’s Hooks feature provides a means to tap into and modify the inner workings of the framework without hacking the core files.
Let’s create a file called
application/views directory with below content:
Site Under Maintenance
Sorry for the inconvenience. To improve our services, we have momentarily shutdown our site.
To use hooks, you need to enable hooks, so edit the
application/config/config.php file and set $config[‘enable_hooks’] to TRUE.
$config['enable_hooks'] = TRUE;
To make it simple to enable and disable the maintenance mode, let’s define a new config variable for maintenance mode. So add the following config code to the
$config['maintenance_mode'] = TRUE;
To let the system know about the maintenance hook, edit the
application/config/hooks.php file and register the maintenance hook.
$hook['pre_system'] = array( 'class' => 'maintenance_hook', 'function' => 'offline_check', 'filename' => 'maintenance_hook.php', 'filepath' => 'hooks' );
In the above config array,
pre_system: One of the available hook point in CI. The hook will be called very early during system execution and which is the good point to show the maintenance page.
class: The name of the class wish to invoke.
function: The method name wish to call.
filename: The filename containing the class/function.
filepath: The name of the directory containing hook script.
Maintenance Hook Class
Let’s create a new hook file called
application/hooks/maintenance_hook.php and add following php code. The following code checks config value of the maintence variable which we have deinfed in
application/hooks/config.php file and if that value is true, it will load the site maintenance page from application views folder.
Enable/Disable Maintenance Mode
Now you can enable the maintenance mode by settings
$config['maintenance_mode'] = TRUE;and to disable the maintenance mode, change it to
$config['maintenance_mode'] = FALSE;.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.