简体   繁体   中英

Yii2 set custom session

I want to add costum session and session values query from user table (database)

where I put Yii::$app->session->set('blabla','1234') ?

If I put in login controller and user is set auto login (not access login), the session can't set

In your app\\components\\User component you could just hook to the afterLogin event

example:

namespace \app\components;

Class User extends \yii\web\User{
   public function afterLogin($identity, $cookieBased, $duration){
      parent::afterLogin($identity, $cookieBased, $duration);
      Yii::$app->session->set('blabla','1234')
   }
}

ref http://www.yiiframework.com/doc-2.0/yii-web-user.html#afterLogin()-detail

put in your config/main.php or web/main.php with 'on afterLogin'

'components' => [ 
...
   'user' => [
        ...
        'on afterLogin' => function($event) {
            if($userId = Yii::$app->session->get('__id')){
                $user = User::findOne($userId);
                Yii::$app->session->set('username', $user->username);
                Yii::$app->session->set('name', $user->name);
                ...
            }
        }
    ],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM