Yii2将行为附加到Application :: EVENT_BEFORE_REQUEST

时间:2018-03-07 17:12:42

标签: php yii2 yii2-advanced-app

我正在尝试检查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');
        }
    }
}

1 个答案:

答案 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'
] ,

请记住将其添加到idcomponents索引定义的同一级别

return [
    'id' => 'app-backend' ,
    'on '.yii\web\Application::EVENT_BEFORE_REQUEST => [
        'backend\components\CheckIfLoggedIn','changeLanguage'
    ] ,

首次尝试在die("hello world");的开头添加changeLanguage,以便您确认它正在输入changeLanguage功能。

希望有所帮助