How to use EVENT_AFTER_LOGIN in yii2 ?

EVENT_AFTER_LOGIN is a constant.

Question : how can it be used to record the time of user logon?

Appendix to the question: why do we need some similar events in this case, when we can record the user's login time, from класса User метода public static function findIdentity ?

Here is what is written, but no example shows how to use this event.

You can use these events to implement the login audit feature, online user statistics. For example, in the handler for EVENT_AFTER_LOGIN, you can record the time and IP address of the entry in the user table.

Well, and of course yes, EVENT_AFTER_LOGIN only works if the login is successful, this is the same if we inserted our date entry method into the Login () method. In general, it is not clear why this is necessary.

  • @ Alexey Shimansky Well, of course yes, EVENT_AFTER_LOGIN only works if the login is successful, this is the same if we inserted our date method into the Login () method. In general, it is not clear why this is necessary. - gilo1212

1 answer 1

If I understand the question correctly.

how to use this event

Well, for example, you can do something like

 if($model->save()){ $model->trigger(User::EVENT_AFTER_LOGIN); } 

that is, to initiate an event of a certain virtual login, which can be applicable, say, when you do pseudo-authorization through some kind of intermediary. Well, for example, the point is that events are triggered where it is beneficial and necessary for us. or you can use it like this:

 $foo->on(НАПРИМЕР_НАСЛЕДОВАННЫЙ_ОТ_USER_КЛАСС::EVENT_AFTER_LOGIN, function ($event) { // логика обработки события логина }); 

If you are interested in why a constant is used, then this is what is said in the manual:

It is advisable to use class constants to indicate event names. In the previous example, the constant EVENT_HELLO stands for the hello event. This approach has three advantages. First, typos are excluded. Secondly, for events, completion works in various development environments. Third, to find out which events are supported by the class, it is enough to check the constants declared in it.

In general, all this is detailed here https://github.com/yiisoft/yii2/blob/master/docs/guide-ru/concept-events.md#Processors- events- on- level- class-