Add Maintenance Mode to Yii 2 Application

Install this extension: https://github.com/brussens/yii2-maintenance-mode

Add to your config file:

'bootstrap' => ['log', 'maintenanceMode'],
...
'components' => [
    'maintenanceMode' => [
        'class' => 'brussens\maintenance\MaintenanceMode',
    ],
    ...
],

Modify according to your needs. Make sure to indicate an allowed user or role. Also create a default route for displaying maintenance mode text. Place in route.

'maintenanceMode' => [
    // Component class namespace
    'class' => 'brussens\maintenance\MaintenanceMode',

    // Mode status
    'enabled' => true,

    // Route to action
    'route' => 'maintenance/index',

    // Allowed user names
    'users' => [
        'BrusSENS',
    ],

Add to your console config file. This is useful when you cannot access your UI:

'bootstrap' => ['log', 'maintenanceMode'],
...
'components' => [
    'maintenanceMode' => [
        'class' => 'brussens\maintenance\MaintenanceMode',
    ],
...
],

Add buttons on UI. You can use session[‘maintenance’] to store current state.

echo '<span style = "color:white;font-weight:bold;">MAINTENANCE</span><br/>';

if (Yii::$app->session['maintenance'] == NULL){
     echo Html::a('ON', ['/site/enable'], ['class'=>'btn btn-primary grid-button']); 
     echo Html::a('OFF', ['/site/disable'], ['class'=>'btn btn-primary grid-button']);
}

if (Yii::$app->session['maintenance'] == 'OFF'){
     echo Html::a('ON', ['/site/enable'], ['class'=>'btn btn-primary grid-button']); 
     echo Html::a('OFF', ['/site/enable'], ['class'=>'btn btn-primary grid-button', 'disabled' => 'disabled']);
}else if (Yii::$app->session['maintenance'] == 'ON') {
     echo Html::a('ON', ['/site/enable'], ['class'=>'btn btn-primary grid-button', 'disabled' => 'disabled']); 
     echo Html::a('OFF', ['/site/disable'], ['class'=>'btn btn-primary grid-button']); 
}

Add to controller. Make sure to change the state stored in maintenance when a function is called:

public function actionEnable()
{ 
     Yii::$app->session['maintenance'] = 'ON';
     Yii::$app->maintenanceMode->enable();

     return $this->goHome();
}
public function actionDisable()
{
     Yii::$app->session['maintenance'] = 'OFF';
     Yii::$app->maintenanceMode->disable();

return $this->goHome();
}

maintenance