Yii2 - Getting an unknown property: yii \ console \ Application :: user

I try to start the console controller from the terminal, but I get these errors every time

Error: Getting unknown property: yii\console\Application::user 

here is the controller

 class TestController extends \yii\console\Controller { public function actionIndex() { echo 'this is console action'; } } 

and this is a consistent configuration

 return [ 'id' => 'app-console', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'controllerNamespace' => 'console\controllers', 'modules' => [], 'components' => [ 'log' => [ 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning'], ], ], ], ], 'params' => $params]; 

I tried to run it using these commands with no luck

 php yii test/index php yii test php ./yii test 

can anyone help?

+5
source share
3 answers

The console application does not have Yii->$app->user . 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' ], ....... ] 

See below for more details about your problem: Link

OR

Follow the link below: Yii2 isGuest gives an exception in the console application

Note. There is no session in the console application.

+9
source

Install in \ console \ config \ main.php

 return [ 'id' => 'app-console', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'controllerNamespace' => 'console\controllers', 'components' => [ 'log' => [ 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning'], ], ], ], 'user' => [ 'class' => 'yii\web\User', 'identityClass' => 'app\models\Credential',// class that implements IdentityInterface //'enableAutoLogin' => true, ], ], 'params' => $params, ]; 

now in your \ console \ controller \ AbcController.php add the init method

  public function init() { parent::init(); Yii::$app->user->setIdentity(Credential::findOne(['id'=><cronloginid>])); } 

create a cron account and pass this login id to a variable with this configuration, your Blamingable of yii2 behavior will work

+4
source

As @GAMITG said, you must configure the custom component in the configuration file, but unfortunately you cannot access the session in the console because the session is not available in the console. Perhaps you could solve this problem as follows:

 $user_id = isset(Yii::$app->user->id) ? Yii::$app->user->id : 0; 
0
source

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


All Articles