Yii2 Dynamic Maintenance Mode

4.9k views Asked by At

I've used the following library in my Yii2 project: Click here

I've set it up and tested it and it works great. But now I want to make it dynamic as in if an admin clicks on a toggle switch the website should go into maintenance mode. To make it happen all I need to do is to make the enabled variable true which is used in Maintenance class of this library.

But my question is how can I link my toggle switch to that variable.

Thanks in advance!

2

There are 2 answers

0
Ali MasudianPour On BEST ANSWER

You can access to application's components like below:

Yii::$app->componentName

So, with this component you can access it like below:

Yii::$app->maintenanceMode->enable=FALSE;
0
lubosdz On

Setting Yii2 site into maintenance mode means forcing route before processing the request. This can simply be done via config on beforeRequest closure:

in /config/web.php

return [
    ...
    'bootstrap' => ['log'],
    'on beforeRequest' => function ($event) {
        if (Yii::$app->params['portalMode'] == 'maintenance') {
            $letMeIn = Yii::$app->session['letMeIn'] || isset($_GET['letMeIn']);
            if (!$letMeIn) {
                Yii::$app->catchAll = [
                    // force route if portal in maintenance mode
                    'site/maintenance',
                ];
            }else{
                Yii::$app->session['letMeIn'] = 1;
            }
        }
    },
    'components' => [
    ...
]

and in SiteController create action "actionMaintenance":

public function actionMaintenance()
{
    return $this->render('maintenance');
}

and in view views/site/maintenance.php adjust your layout:

<h1>The site is currently under maintenance</h1>
<p>We apologize for inconvenience. Please come back later.</p>

See also related post.