How do I set the user status (online/offline) in a Yii-2 application

天大地大妈咪最大 提交于 2021-01-29 03:27:55

问题


For this I wrote a function in the Gii generated User model which sets the 'status' field of the corresponding user table as follows

public function setStatus()
    {
     if (!\Yii::$app->user->isGuest) {
     $this->status = 1;
     }
     else {
         $this->status = 0;
     }
    }

Now in my Controller :

public function actionLogout()
    {
        $usr = new \frontend\models\User;
        $usr->setStatus();

        Yii::$app->user->logout();

        return $this->goHome();

    }

But Yii throws an error:

Cannot redeclare frontend\models\User::tableName();

I tried to echo all the autoloaded classes but the class is not autoloaded. How do I go about this?


回答1:


As for your error, check this related question.

Most likely you defined it twice in this class, and you don't use IDE because majority of them highlight this kind of errors.

As for status - this doesn't make sense. Using Yii::$app->user->isGuest check is enough for determing if user is logged or guest. But this is not suitable for determing if user is online / offline.

As for this problem, there are similar questions asked before, check for example this question.

And finally, don't use hardcoded statuses, declare them as constants in model instead:

const STATUS_OFFLINE = 1;
const STATUS_ONLINE = 2;

Usage: self::STATUS_OFFLINE (inside of class where it's declared) or User::STATUS_OFFLINE (don't forget to include namespace in use section).

Update: Considering that user is online only because user is logged in seems not be right. But if need only calculating who is online / offline among logged in users, why you need statuses if there are only two possible options? Use is_online boolean column instead.



来源:https://stackoverflow.com/questions/34753487/how-do-i-set-the-user-status-online-offline-in-a-yii-2-application

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