Yii2 isGuest giving exception in console application

二次信任 提交于 2019-12-23 10:57:51

问题


In console application when I used Yii::$app->user->isGuest it is giving the below exception:

Exception 'yii\base\UnknownPropertyException' with message 'Getting unknown prop
erty: yii\console\Application::user'

I even tried adding the user in components array in config file. But it didn't worked. Any idea what am I doing wrong?


回答1:


In Console application Yii->$app->user does not exist. So, you need to configure user component in config\console.php.

like as,

config\console.php

 'components' => [
 .........
 ......
        'user' => [
            'class' => 'yii\web\User',
            'identityClass' => 'app\models\User',
            //'enableAutoLogin' => true,
        ],
        'session' => [ // for use session in console application
            'class' => 'yii\web\Session'
        ],
 .......
]

To check it works or not using below code.

public function actionIndex($message = 'hello world')
{
    echo $message . "\n";
    $session = \Yii::$app->session->set('name', 'ASG');

    if(\Yii::$app->session) // to check session works or not
        echo \Yii::$app->session->get('name')."\n";

    print_R(\Yii::$app->user);
}

More info about your problem : Link

Note : There's no session in console.




回答2:


The reason is simple. Guide says about application components (user is a component):

user: represents the user authentication information. This component is only available in Web applications Please refer to the Authentication section for more details.

So Yii::$app->user it not available in console applications.

As a consequence you have to consider using this component in model classes that are also used by console applications.

Extra note: it is internally used by BlameableBehavior, however, this makes no problems since user will be null if a model gets saved/created and no user is available.



来源:https://stackoverflow.com/questions/33036766/yii2-isguest-giving-exception-in-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!