Starting from bin / swoft, read the source code of swoft framework (7) — event processor


After the bean processor, most of the components used in our business are placed in the container. When we need to use it, we can get the bean object from the container, which makes our work a lot easier

Let’s first look at the entry method of the event processor

public function handle(): bool
     if (!$this->application->beforeEvent()) {
         CLog::warning('Stop event processor by beforeEvent return false');
         return false; 
     //Get the loaded event manager from the container
     /** @var EventManager $eventManager */
     $eventManager = bean('eventManager');
     //Save the event listening and event subscription instances saved by the listener register to the event manager
     //COUNT1 is the number of listening instances and COUNT2 is the number of subscribing instances
     [$count1, $count2] = ListenerRegister::register($eventManager);
     //Print execution results to console
     CLog::info('Event manager initialized(%d listener, %d subscriber)', $count1, $count2);
     // Trigger a app init event
     //Trigger app initialization completion event
     //End event handler operation
     return $this->application->afterEvent();


Since the event manager has been loaded into the bean container, the current processor works very little, only handing over the collected listener and subscriber objects to the event manager for unified management
In addition, if you want to add an event listener before the event handler is called, you need to add it through the addListener or addsubscriber method of swoft / event / listener register
Event manager, later may be a separate chapter for analysis