Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit fdb8a32

Browse files
committed
feature #3950 [Components][EventDispatcher] describe the usage of the RegisterListenersPass (xabbuh)
This PR was merged into the 2.3 branch. Discussion ---------- [Components][EventDispatcher] describe the usage of the RegisterListenersPass | Q | A | ------------- | --- | Doc fix? | no | New docs? | yes | Applies to | all | Fixed tickets | #3879 Commits ------- 36407e0 describe the usage of the RegisterListenersPass
2 parents 73b8487 + 36407e0 commit fdb8a32

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

components/event_dispatcher/introduction.rst

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,47 @@ instance of ``Symfony\Component\HttpKernel\Event\FilterResponseEvent``::
205205
// ...
206206
}
207207

208+
.. sidebar:: Registering Event Listeners in the Service Container
209+
210+
When you are using the
211+
:doc:`DependencyInjection component </components/dependency_injection/introduction>`,
212+
you can use the
213+
:class:`Symfony\\Component\\HttpKernel\\DependencyInjection\\RegisterListenersPass`
214+
from the HttpKernel component to tag services as event listeners::
215+
216+
use Symfony\Component\DependencyInjection\ContainerBuilder;
217+
use Symfony\Component\DependencyInjection\Definition;
218+
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
219+
use Symfony\Component\HttpKernel\DependencyInjection\RegisterListenersPass;
220+
221+
$containerBuilder = new ContainerBuilder(new ParameterBag());
222+
$containerBuilder->addCompilerPass(new RegisterListenersPass());
223+
224+
// register the event dispatcher service
225+
$containerBuilder->register(
226+
'event_dispatcher',
227+
'Symfony\Component\EventDispatcher\EventDispatcher'
228+
);
229+
230+
// register your event listener service
231+
$listener = new Definition('AcmeListener');
232+
$listener->addTag('kernel.event_listener', array(
233+
'event' => 'foo.action',
234+
'method' => 'onFooAction',
235+
));
236+
$containerBuilder->setDefinition('listener_service_id', $listener);
237+
238+
// register an event subscriber
239+
$subscriber = new Definition('AcmeSubscriber');
240+
$subscriber->addTag('kernel.event_subscriber');
241+
$containerBuilder->setDefinition('subscriber_service_id', $subscriber);
242+
243+
By default, the listeners pass assumes that the event dispatcher's service
244+
id is ``event_dispatcher``, that event listeners are tagged with the
245+
``kernel.event_listener`` tag and that event subscribers are tagged with
246+
the ``kernel.event_subscriber`` tag. You can change these default values
247+
by passing custom values to the constructor of ``RegisterListenersPass``.
248+
208249
.. _event_dispatcher-closures-as-listeners:
209250

210251
.. index::

0 commit comments

Comments
 (0)