web123456

Two ways to use ThinkPHP8 events

  • Generate event class
    1. //Defining a custom Event class is not necessarily an event class, it is OK for ordinary classes, but using event class architecture is clearer
    2. //The following will generate a UserLogin event class in the directory app\event
    3. php think make:event UserLogin

    Write the code as follows:

    1. namespace app\event;
    2. class UserLogin
    3. {
    4. //Hand method name and parameters are customized
    5. public function sendMessage($param)
    6. {
    7. //Processing code
    8. echo('sendmessage');
    9. }
    10. }
  • Generate a subscription class and manually register event listening in the subscribe function
    1. class UserLoginSubscribe
    2. {
    3. // Manual event subscription, the method name must be subscribe, and add events to the event subscriber in the function
    4. public function subscribe(Event $event)
    5. {
    6. //Add events to subscriber The first parameter is the event identifier, write casually, the second parameter is the event class and the executed function
    7. $event->listen('UserLogin',[app('app\event\UserLogin'),'sendMessage']);
    8. //You can also dynamically modify the event logo for the automatic identification function onLogout. The original logo is Logout, but now it is changed to Out
    9. //$event->listen('Out', [$this,'onUserLogout']);
    10. }
    11. }
  • Sign up to subscribe
    1. return [
    2. 'subscribe' => [
    3. 'app\subscribe\UserLoginSubscribe',
    4. // More event subscriptions
    5. ],
    6. ];
  • Call
    1. //Call, the event identifier is the first parameter of $event->listen('UserLogin',[app('app\event\UserLogin'),'sendMessage'])
    2. event('UserLogin');