Using the 'on beforeRequest'
with the \Yii::$app->catchAll
property
in the web.php config double renders pieces of the site.
After updating Yii2 from an older version my maintenance page somewhat broke. For some reason it appears that the head contents, header element, main element, and footer element are re-rendered in some anonymous div after the footer.
I downloaded a fresh copy of the current version of Yii2 to test and I still get the problem.
config/web.php :
$config = [
// The only thing added
'on beforeRequest' => function ($event) {
// I also added 'maintenance' to the config/params.php array and set it to true
if (\Yii::$app->params['maintenance']) {
\Yii::$app->catchAll = ['site/maintenance'];
}
},
//... All the other default config stuff
];
controllers/SiteController.php :
// The only thing added
public function actionMaintenance() {
return $this->render('maintenance');
}
views/site/maintenance.php :
<?php $this->title = "Maintenance"; ?>
<p>The site is in Maintenance Mode<p>
This worked in an older version of my project using an older version of Yii2. I did a large version jump so I’m not sure at what point this stopped working. I’m not sure if this is intended behavior that was perhaps broken in an old version of Yii2. If so, what would be the right way to redirect to a maintenance page?
EDIT:
I came up with a work-around that doesn’t use \Yii::$app->catchAll
config/web.php :
$config = [
'on beforeRequest' => function ($event) {
if (\Yii::$app->params['maintenance'] &&
\Yii::$app->request->url != '/index.php?r=site%2Fmaintenance')
// Change '/index.php?r=site%2Fmaintenance' to '/site/maintenance'
// if the urlManager enables pretty url's and disables script name
{
\Yii::$app->response->redirect(['/site/maintenance']);
}
},
//... All the other default config stuff
];
This works without doubling the render output but I’m not sure how robust it is.