Roland Franssen  - c6dd1cfc8d306af167cbd1a67ca9c569 - Invokable event listeners (Symfony Blog)

In 4 applications it’s recommended to manage events using subscribers
instead of 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:

# config/services.yaml
    tags: [{ name: kernel._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:

use SymfonyComponentHttpKernelEventGetResponseEvent;

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:

# config/routes.yaml
    path: /
    # before Symfony 4.1 you must add the 'templateAction' method name
    controller: 'SymfonyBundleFrameworkBundleControllerTemplateController::templateAction'
    # starting from Symfony 4.1, TemplateController includes an __invoke() method
    controller: 'SymfonyBundleFrameworkBundleControllerTemplateController'
      template: 'homepage.html.twig'

Source link


Please enter your comment!
Please enter your name here