Skip to content

Instantly share code, notes, and snippets.

@Microtribute
Last active September 4, 2020 17:10
Show Gist options
  • Save Microtribute/e1781411cc392112ef92bb1a335eb8bf to your computer and use it in GitHub Desktop.
Save Microtribute/e1781411cc392112ef92bb1a335eb8bf to your computer and use it in GitHub Desktop.
Symfony Kernel Events Default Method Name

How does Symfony determine the name of the method to call in an event listener on a kernel event?

In regard to this question, the official Symfony documentation states:

Symfony follows this logic to decide which method to execute inside the event listener class:

  1. If the kernel.event_listener tag defines the method attribute, that's the name of the method to be executed;

  2. If no method attribute is defined, try to execute the method whose name is on + "camel-cased event name" (e.g. onKernelException() method for the kernel.exception event);

  3. If that method is not defined either, try to execute the __invoke() magic method (which makes event listeners invokable);

  4. If the _invoke() method is not defined either, throw an exception.

There is an optional attribute for the kernel.event_listener tag called priority, which is a positive or negative integer that defaults to 0 and it controls the order in which listeners are executed (the higher the number, the earlier a listener is executed). This is useful when you need to guarantee that one listener is executed before another. The priorities of the internal Symfony listeners usually range from -256 to 256 but your own listeners can use any positive or negative integer.

https://github.com/symfony/event-dispatcher/blob/master/DependencyInjection/RegisterListenersPass.php#L100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment