问题描述
<?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']);
}
},
这篇关于根据数据库结果设置 Yii2 catchAll 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)