How do you properly use the afterLogin event in yii\web\User?

I have a method that I need to run every time a user authenticates either by traditional login (form) or through loginByCookie.

I am able to run the method after traditional login using the login model, but this does not fire when they visit later and are validated through the cookie.

In yii\web\User the afterLogin method fires immediately after successful login either by


login

or by


loginByCookie

. The GitHub Docs clearly mention overriding this method and if the method is overridden, make sure to call the parent implementation. I understand that is how the EVENT_AFTER_LOGIN event is actually triggered.

Questions:

  1. Is the loginByCookie method called every time a page loads?

  2. How do I override the base method? I have tried implementing my own afterLogin method by copying the base method into my User class, but it doesn’t get called.

  3. Would it be better to just use the EVENT_AFTER_LOGIN event instead of overriding the base method? I have read, many, many tutorials on event using the ->on() method, but can’t get it to work inside the User class?

Any help is greatly appreciated.

  1. No. It’s called when there’s no active session with user logged in as far as I remember. Check code to be sure.

  2. You need to extend from framework’s class then in config to override ‘user’ component to use your class instead of framework’s.

  3. Probably yes.