Sometimes, there is a need to fine tune some application settings or restore a database from a backup. When working on tasks such as these, it is not desirable to allow everyone to use the application because it can lead to losing the recent user messages or showing the application implementation details.
In this recipe, we will see how to show everyone except the developer a maintenance message.
Carry out the following steps:
protected/controllers/MaintenanceController.php
. We do this as follows:<?php class MaintenanceController extends CController { public function actionIndex() { $this->renderPartial("index"); } }
protected/views/maintenance/index.php
as follows:<!doctype html> <head> <meta charset="utf-8" /> <title><?php echo CHtml::encode(Yii::app()->name)?> is under maintenance</title> </head> <body> <h1><?php echo CHtml::encode(Yii::app()->name)?> is under maintenance</h1> <p>We'll be back soon. If we aren't back for too long, please drop a message to <?php echo Yii::app()->params['adminEmail']?>.</p> <p>Meanwhile, it's a good time to get a cup of coffee, to read a book or to check email.</p> </body>
protected/config/main.php
as follows:return array( 'catchAllRequest'=>file_exists(dirname(__FILE__).'/.maintenance') && !(isset($_COOKIE['secret']) && $_COOKIE['secret']=="password") ? array('maintenance/index') : null, …
.maintenance
in protected/config/
. After doing it you should see the following:In order to get the application back to normal, you just need to delete it. To view the website in the maintenance mode, you can create a cookie named secret
with value equal to password
.
A Yii web application offers a way to intercept all possible requests and route these to a single controller action. You can do this by setting CWebApplication::catchAllRequests
to an array containing an application route as follows:
'catchAllRequest'=>array('maintenance/index'),
The maintenance controller itself is nothing special; it just renders a view with a text.
We need an easy way to turn the maintenance mode on and off. As the application config is a regular PHP file, we can achieve this with a simple check for the file existence as follows:
file_exists(dirname(__FILE__).'/.maintenance')
In addition, we check for the cookie value to be able to override the maintenance mode. We do this as follows:
!(isset($_COOKIE['secret']) && $_COOKIE['secret']=="password")
In order to learn more about how to catch all requests in a Yii application and check the production-ready solution for maintenance, refer to the following URLs:
3.145.130.31