Yii2 isGuest gives an exception in the console application

In a console application, when I used Yii::$app->user->isGuest , he gave the following exception:

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

I even tried adding the user to the component array in the configuration file. But that did not work. Any idea what I'm doing wrong?

+5
source share
2 answers

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

eg,

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 if it works or not, use the code below.

 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 about your problem: Link

Note. There is no session in the console.

+3
source

The reason is simple. Guide talks about the components of an application (the user is a component):

user: represents user authentication information. This component is available only in web applications. See the Authentication Section for more details.

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

As a result, you should consider using this component in model classes that are also used by console applications.

Note: it is used internally by BlameableBehavior , however this is not a problem as the user will be null if the model is saved / created and the user is not accessible.

+2
source

Source: https://habr.com/ru/post/1233341/


All Articles