Symfony News

New in Symfony 4.1: Invokable event listeners

Roland Franssen

Contributed by
Roland Franssen
in #25275.

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)
    {
        // ...
    }
}

We silently added support for __invoke() in other parts of the framework in past Symfony versions. For example, in Symfony 3.4 we added support for it in the TemplateController:

1
2
3
4
5
6
7
8
9
# config/routes.yaml
index:
    path: /
    # before Symfony 3.4 you must add the 'templateAction' method name
    controller: 'Symfony\Bundle\FrameworkBundle\Controller\TemplateController::templateAction'
    # starting from Symfony 3.4, TemplateController includes an __invoke() method
    controller: 'Symfony\Bundle\FrameworkBundle\Controller\TemplateController'
    defaults:
      template: 'homepage.html.twig'

Be trained by Symfony experts - 2018-01-29 Clichy - 2018-01-29 Clichy - 2018-01-31 Clichy


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook