Problem with isGuest

Having a problem with isGuest.




namespace app\components;

	

use Yii;

use yii\behaviors\TimestampBehavior;

use yii\db\Expression;

	

class ActiveRecord extends \yii\db\ActiveRecord {


}



Class setup as above. Using …




Yii::$app->user->isGuest



Results in following error message …

Undefined property: yii\web\User::$isGuest

Any ideas why?

‘components’ =>

    'user' => [


        'identityClass' => 'app\models\User'


    ],

Hi,

Yes my setup is set up like that. Still the problem persists though.

Please note the isGuest works in other areas of the system like the controllers and views. But not in the Model shown in the first post.

James.

it doesn’t make any logic, as yii\Application works like locator (register+factory+strategy) so it must be accessible at any time after app’s run() execution.

I have tested it in ActiveRecord class and works fine :)

An update to this, now I have tested it in the class beforeSave method and it works.

The only place it is not working is in the behaviors methods.




public function beforeSave() {


echo Yii::$app->user->isGuest;

return true;


}



Works fine.




public function behaviors() {


echo Yii::$app->user->isGuest;

return [];


}



Generates error.

Any ideas why?

My only guess after crawling the source code (isGuest is a magic property) is that your behaviours function is called before the User object has been constructed, in which case the isGuest property does not exist yet since it is actually implemented as a magic method in yii\base\Object.

You could see if it works by calling getIsGuest() as a function, which is actually defined in User and see if that gets around your problem but if you are calling it too early, it sounds like it will always return true anyway.

The only workaround I can think of is to pull the isGuest out into the behaviour class itself rather than in the behaviors() function. This way, by the time the behaviour functionality is actually invoked, the user will be known and loaded, effectively moving the logic up another level.

Ok thanks for the your thoughts.

I have decided to use beforeSave and afterFind to do the same task as the behaviors would have done though.