Custom event handler for afterLogin

Hi there,

Can you please provide an example of how I can properly attach a function to the afterLogin event from web user class? The only examples I’ve seen so far involve modifying the web user class itself.

Thanks

you can add a handler on config file




'user' => [

            'identityClass' => 'app\models\User',

            'on afterLogin' => 'your_function_name', //this is a PHP Callback

            'enableAutoLogin' => true,

        ],



That’s fantastic, totally got me on track to solve my problem.

My issue was with the fact that I am using yii2-user and so had removed user from component config and just had user config under module. I placed the component user config back in and it all seems to work so far. Here’s the code for anyone who might be interested.

web.php




    'components' => [

        'user' => [

            'identityClass' => 'app\models\User',

            'on afterLogin' => ['app\events\AfterLoginEvent', 'handleNewUser'],

            'loginUrl'        => ['/user/security/login'],

            'enableAutoLogin' => true,

        ],

..........

    'modules' => [

        'user' => [

            'class' => 'dektrium\user\Module',

            'modelMap' => [

                'User' => 'app\models\User',

                'LoginForm' => 'app\models\LoginForm',

            ],



events/AfterLogin/Event.php




namespace app\events;

class AfterLoginEvent{

    // public AND static

    public static function handleNewUser($event)

    {

        echo "Great success!";

    }

}



Thanks for your help Reza, much appreciated!

You can use below code:




namespace app\bootstraps;


class AppBootstrap implments yii\base\BootstrapInterface{


   public function bootstrap($app){

      $app->user->on(\yii\web\User::EVENT_AFTER_LOGIN,['app\events\AfterLoginEvent::handleNewUser']);

   }

}



And add bellow line to your config




'bootstrap'=>['app\bootstraps\AppBootstrap']



Above source code no need user compoment config. Some extension like yii2-user must remove user config

Thanks Reza,

That’s a much better solution. I’m still trying to get my head around events as I haven’t used them outside of JS before.

I had to change the bootstrap function to:




public function bootstrap($app){

      $app->user->on(\yii\web\User::EVENT_AFTER_LOGIN,['app\events\AfterLoginEvent', 'handleNewUser']);

   }



otherwise I would get the following error:

call_user_func_array() expects parameter 1 to be a valid callback

I’m reading the yii2 guide on events and it seems that your bootstrap function would require that function to be registered globally. Do you know if there is any significant difference doing it either way?

Cheers