Events
Monti includes a minimal, custom event system used internally by the framework and available to your own code.
Concepts
An event is identified by its name (a string) and holds a list of listeners. Listeners are added independently of dispatching, and are invoked, in registration order, every time the event is dispatched.
// register a listener
\App\System\Events\Manager::getEvent("my.custom.event")->addListener(function($payload) {
// ...
});
// dispatch it, passing any number of arguments to the listeners
\App\System\Events\Manager::getEvent("my.custom.event")->dispatch($payload);
Listeners
A listener can be a closure, any other callable, or the fully qualified name of a class exposing a dispatch() method. In this case Monti instantiates the class and calls its dispatch() method with the same arguments:
class SendWelcomeEmail {
public function dispatch($user) {
// ...
}
}
\App\System\Events\Manager::getEvent("users.onSignup")->addListener(SendWelcomeEmail::class);
Use setListener() instead of addListener() to replace every existing listener with a single one.
Events emitted by the framework
| Event | Dispatched when | Arguments |
|---|---|---|
system.onBooted |
The framework has finished booting, right before dispatching the request to the router | none |
router.onRouteMatch |
A route has matched the current request, right before its handler runs | the matched \App\System\Router\Route |
router.onRouteHandled |
The matched route's handler has finished and produced a response | the \App\System\Router\Route and the response it produced |
router.onNotFound |
No route matches the current request | the request method and path |
users.onSignup |
A new user completes the signup flow | the newly created \App\Modules\Users\User |
users.onLogout |
A user logs out | the \App\Modules\Users\User who logged out |
Event names are internally stripped of whitespace, so "my event" and "myevent" resolve to the same event.