發現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 } ], ...]