Minor [PHP framework] 5. Events, minorphp framework events
5.1 Event
Minor'sEvent
Class provides a simple observer implementation that allows you to subscribe to and listen to events in the application.
5.1.1 subscribe to events
First, create an event class:
<?phpnamespace App\Event;use Minor\Event\Event;class DemoEvent extends Event{ private $name; public function __construct($name) { $this->name = $name; } public function setName($name) { $this->name = $name; } public function getName() { return $this->name; }}
Then register the event in the configuration file:
<?phpreturn $events = [ 'App\Event\DemoEvent' => [ 'App\Listener\DemoListener' => 'handle', ],];
5.1.2 trigger event
Minor provides an Event management class: Minor \ event \ EventManger. by calling the static method fire: EventManager: fire ($ Event) of this class, this event can be triggered. For example:
class FooController extends Controller{ public function bar($productName) { $event = new DemoEvent('DemoEvent'); EventManager::fire($event); ... }}
5.2 listener
After an event is triggered, the event manager EventManager triggers the listener through the configuration file. In the 5.1.1 configuration file, we configured the DemoEvent Listener as App \ Listener \ DemoListener's handle method. You can see the implementation of this class:
<?phpnamespace App\Listener;use App\Event\DemoEvent;use Minor\Event\Listener;class DemoListener extends Listener{ public function handle(DemoEvent $event) { echo '[DemoListener] handle the event:[' . $event->getName() .'] success!<br/><br/>'; }}