本文介绍了根据数据库结果设置Yii2 catchAll路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?php

namespace app\modules\site\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\models\SiteSettings;

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属性。初始化方法在更改控制器的位置后执行,因此不会产生任何效果。您需要使用应用程序的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']);
    }
},

这篇关于根据数据库结果设置Yii2 catchAll路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 23:16