Home >Backend Development >PHP Tutorial >PHP framework Minor5 event (with code)
5.1 Event
Minor’s Event
class provides a simple observer implementation, allowing you to subscribe to and listen for events in your application.
5.1.1 Subscribe to events
First create an event class:
<?php namespace App\Event;use Minor\Event\Event;class DemoEvent extends Event {private$name;publicfunction __construct($name) {$this->name = $name; }publicfunction setName($name) {$this->name = $name; }publicfunction getName() {return$this->name; } }
Then register this event in the configuration file:
<?phpreturn$events = ['App\Event\DemoEvent' => ['App\Listener\DemoListener' => 'handle', ],];
5.1.2 Trigger events
Minor provides an event Management class: MinorEventEventManger, this event can be triggered by calling the static method fire of this class: EventManager::fire($event), for example:
class FooController extends Controller {publicfunction bar($productName) {$event = new DemoEvent('DemoEvent'); EventManager::fire($event);... } }
5.2 Listener
When the event is triggered, the event manager EventManager The listener's formulation method will be triggered through the configuration file. In the 5.1.1 configuration file, we configured the DemoEvent listener as the handle method of AppListenerDemoListener. You can take a look at the implementation of this class:
<?php namespace App\Listener;use App\Event\DemoEvent;use Minor\Event\Listener;class DemoListener extends Listener {publicfunction handle(DemoEvent $event) {echo '[DemoListener] handle the event:[' . $event->getName() .'] success! '; } }
The above introduces the content of the Minor5 event of the PHP framework (with code) , I hope it will be helpful to friends who are interested in PHP tutorials.