根据数据库结果设置 Yii2 catchAll 路由

2022-01-07 00:00:00 routes php yii2
<?php

namespace appmodulessitecontrollers;

use Yii;
use yiifiltersAccessControl;
use yiiwebController;
use appmodelsSiteSettings;

class CommonController extends Controller {

public function init() {
    Yii::$app->language = 'bg-BG';
    Yii::$app->formatter->locale = 'bg-BG';
    Yii::$app->params['siteSettings'] = SiteSettings::find()->one();

    if (Yii::$app->params['siteSettings']->in_maintenance == 1) {
        Yii:$app->catchAll = ['index/maintenance', 'message' => Yii::$app->params['siteSettings']->maintenance_message];
    }
}

}

我试图从 CommonController init 方法中设置 catchAll 路由,但它抛出了一个错误:

I tried to set the catchAll route from within the CommonController init method, but it throws me an error:

从空值创建默认对象

是否可以根据数据库提供的条件设置 catchAll 路由?

Is it possible to set the catchAll route on condition provided from the database?

推荐答案

您需要在处理请求之前设置 catchAll 属性.init 方法是在重新设置控制器后执行的,所以不会有任何影响.您需要使用应用程序 onBeforeRequest 事件来设置 catchAll 路由.

You need to setup catchAll property just before request is handled. Init method is executed after resloving controller, so it won't have any effect. You need to use application onBeforeRequest event to setup up catchAll route.

在配置文件中设置如下:

In config file set following:

$config = [
    'id' => '...',
     ......

    'on beforeRequest' => function () {
        Yii::$app->params['siteSettings'] = SiteSettings::find()->one();            
        if (Yii::$app->params['siteSettings']->in_maintenance == 1) {
            Yii::$app->catchAll = [
              'index/maintenance', 
              'message' => Yii::$app->params['siteSettings']->maintenance_message
            ];
        }
    },
    ....
    'comonents' = [
        ....
    ]
];

您可以通过缓存 SiteSettings::find()->one() 对此进行一些改进;避免为每个请求打开与数据库的连接.

You can add little improvement to this by caching SiteSettings::find()->one(); to avoid opening connection to database for every request.

更新:我不确定 catchAll 是否可以用于特定模块,但您可以处理 onBeforeAction 事件并重定向到自定义路由.

Update: I am not sure if catchAll can be used for specific module, but you can handle onBeforeAction event and redirect to custom route.

'on beforeAction' => function ($event) {

    $actionId = $event->action->id;
    $controllerId = $event->action->controller->id;
    $moduleId = $event->action->controller->module->id;

    //TODO: Check module here
    if (!(($controllerId == "site") && ($actionId == "offline")))
    {
        return Yii::$app->response->redirect(['site/offline']);
    }
},

相关文章