YII2怎麼使用afterLogin和beforLogin自動更新上次登入時間?

來源:互聯網
上載者:User

發現Yii2有afterLogin和beforLogin兩個方法(事件),但是不知道怎麼才能使用。

在User模型我已經寫了如下代碼:

phppublic function behaviors()    {        return [            'timestamp' => [                'class' => TimestampBehavior::className(),                'attributes' => [                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'activated_at', 'updated_at'],                    ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at'                ],            ]        ];    }

因為ActiveRecord裡只有資料庫增刪改查的事件,把yii\web\User::EVENT_AFTER_LOGIN加在這兒也沒用。。。

回複內容:

發現Yii2有afterLogin和beforLogin兩個方法(事件),但是不知道怎麼才能使用。

在User模型我已經寫了如下代碼:

phppublic function behaviors()    {        return [            'timestamp' => [                'class' => TimestampBehavior::className(),                'attributes' => [                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'activated_at', 'updated_at'],                    ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at'                ],            ]        ];    }

因為ActiveRecord裡只有資料庫增刪改查的事件,把yii\web\User::EVENT_AFTER_LOGIN加在這兒也沒用。。。

首先明確兩點
* 你的User Model是繼承自 ActiveRecord
* afterLogin 和 beforeLogin 是 yii\web\User 的兩個事件

那麼你把 yii\web\User 的兩個事件掛載在 User Model 肯定不會去觸發了。

那麼就可以通過配置來解決,我們知道,配置是支援事件掛載的;
例如:

'components' =>[    ...    'user' => [        'identityClass' => 'common\models\User',        'enableAutoLogin' => true,        'on beforeLogin' => function($event) {            $user = $event->identity; //這裡的就是User Model的執行個體了            $user->last_login_at = time();            $user->save();            ...        },        'on afterLogin' => function($event) {            //the same        }    ],    ...]
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.