如何使用Yii 2中的beforeRequest将访客重定向到登录页面?

时间:2017-02-23 19:58:05

标签: php yii yii2-advanced-app

我有问题。我使用RequestBehavior.php中创建的common\components(由Artem Voitko创建的修改后的AccessBehavior.php),但我不知道如何将访客重定向到frontend/web/index.php?r=site%2Flogin

这是RequestBehavior.php的代码:

<?php
/*
 * In configuration file
 * ...
 * 'as AccessBehavior' => [
 *    'class' => '\app\components\AccessBehavior'
 * ]
 * ...
 * (c) Artem Voitko <r3verser@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace common\components;
use yii\base\Behavior;
use yii\console\Controller;
use yii\helpers\Url;
use yii\web\Application;
/**
 * Redirects all users to login page if not logged in
 *
 * Class AccessBehavior
 * @package app\components
 * @author  Artem Voitko <r3verser@gmail.com>
 */
class RequestBehavior extends Behavior
{
    /**
     * Subscribe for events
     * @return array
     */
    public function events()
    {
        return [
            Application::EVENT_BEFORE_REQUEST => 'beforeRequest'
        ];
    }
    /**
     * On event callback
     */
    public function beforeRequest()
    {
        if (\Yii::$app->getUser()->isGuest &&
            \Yii::$app->getRequest()->url !== Url::to(\Yii::$app->getUser()->loginUrl)
        ) {
            \Yii::$app->getResponse()->redirect(\Yii::$app->getUser()->loginUrl);
        }
    }
}
?>

使用它,显示此错误:

Unable to resolve the relative route: site/login. No active controller is available.

我尝试使用beforeAccess,但我需要在请求之前重定向。我需要帮助。

0 个答案:

没有答案