symfonyevent-listenerservice-object

What is the goal of the tags in service settings in symfony2


In this service for an eventListener, it used the tags item:

services:
    app.exception_listener:
        class: AppBundle\EventListener\ExceptionListener
        tags:
            - { name: kernel.event_listener, event: kernel.exception }
  1. What is the goal of tags item?
  2. How define the name (name:kernel.event_listener) into this tags item?

Solution

  • Tags provide a name-key-value attribute that can be attached to a service. By themselves, they don't do anything, but other services can take advantage of tags to do something more interesting.

    In the particular example you've given, when the container is built, a compiler pass for the event listener looks for services with the name kernel.event_listener, and registers that services as an event listener for the kernel.exception event.

    Tag names themselves aren't defined anywhere; but if you create a CompilerPass that's registered with the container, you can search for services that are tagged with a particular name and do something useful with them. (Such as registering event handlers, as described above.)

    You can find more information about tagged services from the Symfony documentation, including an example of a simple CompilerPass.