January 26, 2018 Javier Eguiluz

In Symfony 4 applications it's recommended to manage events using subscribers instead of listeners because only subscribers are automatically configured when using service autoconfiguration.

However, for those still wanting to use listeners, in Symfony 4.1 we improved them to support the __invoke() PHP magic method. Consider the following service configuration:

1 2 3 # config/services.yaml App\EventListener\UserListener : tags : [{ name : kernel.event_listener , event : kernel.request }]

When the kernel.event_listener tag doesn't define the method attribute, Symfony executes the method whose name is on + CamelCased event name. In this example, the onKernelRequest() method will be executed. In Symfony 4.1, if the event listener class doesn't define that method, Symfony looks for the __invoke() method and executes it if it's found.

In practice, in Symfony 4.1 the UserListener class could be simply:

1 2 3 4 5 6 7 8 9 use Symfony\Component\HttpKernel\Event\GetResponseEvent ; class UserListener { public function __invoke ( GetResponseEvent $event ) { // ... } }

Related to this, we've silently added support for __invoke() in other parts of the framework, such as the TemplateController :