Skip to content

[Components][EventDispatcher] describe the usage of the RegisterListenersPass #3950

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 16, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions components/event_dispatcher/introduction.rst
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,47 @@ instance of ``Symfony\Component\HttpKernel\Event\FilterResponseEvent``::
// ...
}

.. sidebar:: Registering Event Listeners in the Service Container

When you are using the
:doc:`DependencyInjection component </components/dependency_injection/introduction>`,
you can use the
:class:`Symfony\\Component\\HttpKernel\\DependencyInjection\\RegisterListenersPass`
from the HttpKernel component to tag services as event listeners::

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\HttpKernel\DependencyInjection\RegisterListenersPass;

$containerBuilder = new ContainerBuilder(new ParameterBag());
$containerBuilder->addCompilerPass(new RegisterListenersPass());

// register the event dispatcher service
$containerBuilder->register(
'event_dispatcher',
'Symfony\Component\EventDispatcher\EventDispatcher'
);

// register your event listener service
$listener = new Definition('AcmeListener');
$listener->addTag('kernel.event_listener', array(
'event' => 'foo.action',
'method' => 'onFooAction',
));
$containerBuilder->setDefinition('listener_service_id', $listener);

// register an event subscriber
$subscriber = new Definition('AcmeSubscriber');
$subscriber->addTag('kernel.event_subscriber');
$containerBuilder->setDefinition('subscriber_service_id', $subscriber);

By default, the listeners pass assumes that the event dispatcher's service
id is ``event_dispatcher``, that event listeners are tagged with the
``kernel.event_listener`` tag and that event subscribers are tagged with
the ``kernel.event_subscriber`` tag. You can change these default values
by passing custom values to the constructor of ``RegisterListenersPass``.

.. _event_dispatcher-closures-as-listeners:

.. index::
Expand Down