Problem with isGuest


\Yii::$app->user->isGuest - always makes a query to the database ( I see from the debugger - SELECT * FROM t_users WHERE id=‘1’)

Why it is constantly making a query? maybe I did something wrong. yii version 2.0.9

Good day to all

The identity of the user must be verified on each request because users might be removed/inactivated between consecutive requests. You can modify the default implementation of yii\web\IdentityInterface::findIdentity() but I wouldn’t recommend that.

Thanks, so I have only one solution it’s add cache for this result with expire. I’m right?

Or simply leave it as is. Fetching one row by its primary key is pretty cheap. It shouldn’t be a performance bottleneck in normal circumstances.

If you really need it you can check if

Yii::$app->user->getIdentity(false) === null

If this is true you are dealing with Guest but remember that since this will not call for authStatus renew you can get old information here like phtamas said.

For example: if You have a few enpoints in the balancer and You have more than 5000 users online, so 5000 unnecessary queries per second it’s too bad.

to be honest I’m disappointed in yii2 IdentityInterface :(

It has nothing to do with Yii2 or IdentityInterface. Theres’s simply no other way to know if user still exists and is active/is not banned/etc. but to query the persistent storage on every request. Caching this information is a security risk. Very short-term caching might be OK, depending on your application’s requirements but you have to implement it yourself.