Events
Masonite ships with a "pub and sub" style events feature that allows you to subscirbe to various events and run listeners, or additional logic, when those events get emitted.

Creating an Event

The first step in events is creating an event to listen to.
Events are simple classes that you can create wherever you like:
1
$ python craft event UserAdded
Copied!
This will create a simple class we can later emit

Creating A Listener

The listener will run the logic when the event is emitted. You can create as many listeners as you like and register as many listeners to events as you need to.
To create a listener simply run the command:
1
$ python craft listener WelcomeEmail
Copied!
This will create a class like this:
1
class WelcomeEmail:
2
def handle(self, event):
3
pass
Copied!

Handle Method

The handle method will run when the listener runs. It will pass the event as the first parameter and any additional arguments that are emitted from the event as additional parameters.

Registering Events and Listeners

After your events and listeners are created you will need to register them to the event class.
You can do this via a service provider:
1
class EventsProvider(Provider):
2
def register(self):
3
self.application.make('event').listen(UserAddedEvent, [WelcomeListener])
Copied!

Firing Events

To fire an event you can use the fire method from the Event class:
1
from app.events import UserAddedEvent
2
from masonite.events import Event
3
4
class RegisterController:
5
def register(self, event: Event):
6
# Register user
7
event.fire(UserAddedEvent)
Copied!

Building a Welcome Email Listener

As an example, to build a listener that sends an email:
First, create the listener:
1
$ python craft listener WelcomeEmail
Copied!
Then we can build out the listener.
To send an email we will need to import the mailable class and send the email using the mail key from the container:
1
from app.mailables.WelcomeMailable import WelcomeMailable
2
3
class WelcomeEmail:
4
def handle(self, event):
5
from wsgi import application
6
7
application.make("mail").send(
8
WelcomeMailable().to('[email protected]')
9
)
Copied!
You can then register the event inside the provider:
1
class EventsProvider(Provider):
2
def register(self):
3
self.application.make('event').listen(UserAddedEvent, [WelcomeListener])
Copied!
When you emit the UserAdded event inside the controller, or somewhere else in the project, it will now send this email out.
You can register as many listeners to the events as you like by simply adding more listeners to the list.
Last modified 7mo ago