How to use events in yii2?

前端 未结 3 1939
时光说笑
时光说笑 2020-11-30 18:42

I\'ve been through the documentation and all the articles on Yii2 events found using Google. Can someone provide me a good example of how events can be used in

3条回答
  •  误落风尘
    2020-11-30 19:26

    For "global" events.

    Optionally you can create a specialized event class

    namespace  your\handler\Event\Namespace;
    class EventUser extends Event {
       const EVENT_NEW_USER = 'new-user';
    }
    

    define at least one handler class:

    namespace  your\handler\Event\Namespace;
    class handlerClass{
        // public AND static
        public static function handleNewUser(EventUser $event)
        {
            // $event->user contain the "input" object
            echo 'mail sent to admin for'. $event->user->username;
        }
    }
    

    Inside the component part of the config under (in this case) the user component insert you event:

    'components' => [
      'user' => [
        ...
        'on new-user' => ['your\handler\Event\Namespace\handlerClass', 'handleNewUser'],
      ],
      ...
    ]
    

    Then in your code you can trigger the event:

    Yii::$app->user->trigger(EventUser::EVENT_NEW_USER, new EventUser($user));
    

    ADD

    You can also use a closure:

    • allows IDE to "detect" the use of the function (for code navigation)
    • put some (small) code that manage the event

    example:

    'components' => [
      'user' => [
        ...
        'on new-user' => function($param){ your\handler\Event\Namespace\handlerClass::handleNewUser($param);},
        'on increment' => function($param){ \Yii::$app->count += $param->value;},
      ],   
      ... 
    ]
    

提交回复
热议问题