Symfony Events and Event Subscribers

Symfony has a powerfully simple event system which makes it very easy to hook into the request lifecycle to handle things like authentication, validation and exception handling

Event Listeners vs Subscribers

An event listener and subscriber are basically the same concept however a listener must be manually configured in services.yml whereas a subscriber will be autowired. We always use the subscriber approach.

Creating an Event Subscriber

You should use the Maker bundle

Note

Note you must have already configured Maker Bundle

1
./bin/console make:subscriber

Your class name should be ThingItDoesSubscriber which will assists in clarity where we may have multiple subscribers for the same Event. The name should be suffixed with Subscriber

Choosing Which Event to Hook Into

You should have a look at the symfony events reference

Each event has it's own event object with different things available, so you may need to experiment a bit to find the perfect one for your requirements

Common Use Cases

There are some very common usecases which are worth documenting

Exception Handling

//TODO