我正在尝试检查Application::EVENT_BEFORE_REQUEST
上的Cookie。我所做的是覆盖events
模型中的Behavior
函数,并在上面提到的事件上返回自定义函数checkLanguage
。我在我的控制器中触发as beforeRequest
(首先我尝试了backend/config/main.php
,但似乎无法从那里到达CheckIfLoggedIn
类)并且请求转到public function events()
课程中的CheckIfLoggedIn
但未进入checkLanguage
功能。
这是我的SiteController
行为:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index', 'language'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
'as beforeRequest' => [
'class' => 'backend\components\CheckIfLoggedIn'
]
];
}
和CheckIfLoggedIn.php
类:
<?php
namespace backend\components;
use yii\base\Behavior;
use yii\web\Application;
class CheckIfLoggedIn extends Behavior
{
public function events()
{
return [
Application::EVENT_BEFORE_REQUEST => "changeLanguage"
];
}
public function changeLanguage()
{
if(\Yii::$app->getRequest()->getCookies()->has('lang')){
\Yii::$app->language = \Yii::$app->getRequest()->getCookies()->getValue('lang');
}
}
}
答案 0 :(得分:1)
问题是你试图在行为中的控制器级别附加Application
事件,而文档说你应该使用Application
配置。
进行以下更新,从班级中删除events()
功能。
backend/components/CheckIfLoggedIn.php
namespace backend\components;
use yii\base\Behavior;
class CheckIfLoggedIn extends Behavior
{
public function changeLanguage()
{
if(\Yii::$app->getRequest()->getCookies()->has('lang')){
\Yii::$app->language = \Yii::$app->getRequest()->getCookies()->getValue('lang');
}
}
}
并将以下内容添加到 common/config
或 backend/config
,如果只需要backend
'on '.yii\web\Application::EVENT_BEFORE_REQUEST => [
'backend\components\CheckIfLoggedIn','changeLanguage'
] ,
请记住将其添加到id
或components
索引定义的同一级别
return [
'id' => 'app-backend' ,
'on '.yii\web\Application::EVENT_BEFORE_REQUEST => [
'backend\components\CheckIfLoggedIn','changeLanguage'
] ,
首次尝试在die("hello world");
的开头添加changeLanguage
,以便您确认它正在输入changeLanguage
功能。
希望有所帮助