Extending Bolt / Event Dispatcher
Note: You are currently reading the documentation for Bolt 5.0. Looking for the documentation for Bolt 5.2 instead?
During the execution of a Symfony/Bolt application, lots of event notifications are triggered. Your project can create and listen to these notifications and respond to them by executing any piece of code.
Listening to events¶
Symfony allows two distinct ways for executing code in response to an event: Listeners and Subscribers.
While similar in what they accomplish, there are a couple of differences that may sometimes sway you to use a listener or a subscriber:
- Subscribers are easier to reuse because the knowledge of the events is kept in the class rather than in the service definition. This is the reason why Symfony uses subscribers internally;
- Listeners are more flexible because bundles can enable or disable each of them conditionally depending on some configuration value.
- Listeners require further configuration in the
services.yaml
file. Subscribers do not.
Due to the last difference (see above), the recommended way in Bolt is to use subscribers, unless you have a good reason for preferring listeners.
Creating an event subscriber¶
Each subscriber has two required components:
- An event or events it subscribes to (i.e., in when does your custom code execute)
- A handler or handlers that contain the custom code in response to the triggered event.
The list of available events is available by running php bin/console debug:event-dispatcher
You can put subscribers in the src
folder in the root of your Bolt project, like so:
Creating a custom event¶
Assuming there is a class that handles custom work in your project,
called CustomWorker
, you can use the EventDispatcher
service to create an event.
First, we need a new Event
object. For example, here is Bolt's own ContentEvent
:
Now, we can dispatch (also known as trigger) that event in the example CustomWorker
class:
Read more about this topic in Symfony's official documentation: Event Dispatcher.
Couldn't find what you were looking for? We are happy to help you in the forum, on Slack or on Github.