Skip to content

Commit 9a6dab7

Browse files
committed
Completed the cookbook about the event subscriber
1 parent 0184e0f commit 9a6dab7

File tree

1 file changed

+51
-61
lines changed

1 file changed

+51
-61
lines changed

cookbook/event_dispatcher/event_listener.rst

Lines changed: 51 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,25 @@ How to Create Event Listeners and Subscribers
66
=============================================
77

88
Symfony has various events and hooks that can be used to trigger custom
9-
behavior in your application. Those events are thrown by the HttpKernel
10-
component and can be viewed in the :class:`Symfony\\Component\\HttpKernel\\KernelEvents` class.
9+
actions in your application. Those events are thrown by the HttpKernel
10+
component and they are defined in the :class:`Symfony\\Component\\HttpKernel\\KernelEvents`
11+
class.
1112

12-
To hook into an event and add your own custom logic, you have to create
13-
a service that listens to that event. You can do that in two different ways,
14-
creating an event listener or an event subscriber instead. In this entry,
15-
you will see the two ways of creating a service that will act as an exception
16-
listener, allowing you to modify how exceptions are shown by your application.
17-
The ``KernelEvents::EXCEPTION`` event is just one of the core kernel events.
13+
To hook into an event and execute your own custom logic, you have to create
14+
a service that listens to that event. As explained in this article, you can do
15+
that in two different ways: creating an event listener or an event subscriber.
16+
17+
The examples of this article only use the ``KernelEvents::EXCEPTION`` event for
18+
consistency purposes. In your own application you can use any event and even mix
19+
several of them in the same subscriber.
1820

1921
Creating an Event Listener
2022
--------------------------
2123

22-
The most common way to listen to an event is to register an event listener::
24+
The most common way to listen to an event is to register an **event listener**::
2325

24-
// src/AppBundle/EventListener/ExceptionListener.php
25-
namespace AppBundle\EventListener;
26+
// src/AppBundle/Listener/ExceptionListener.php
27+
namespace AppBundle\Listener;
2628

2729
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
2830
use Symfony\Component\HttpFoundation\Response;
@@ -78,44 +80,50 @@ using a special "tag":
7880
# app/config/config.yml
7981
services:
8082
kernel.listener.your_listener_name:
81-
class: AppBundle\EventListener\AcmeExceptionListener
83+
class: AppBundle\Listener\ExceptionListener
8284
tags:
83-
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
85+
- { name: kernel.event_listener, event: kernel.exception }
8486
8587
.. code-block:: xml
8688
8789
<!-- app/config/config.xml -->
88-
<service id="kernel.listener.your_listener_name" class="AppBundle\EventListener\AcmeExceptionListener">
89-
<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
90+
<service id="kernel.listener.your_listener_name" class="AppBundle\Listener\ExceptionListener">
91+
<tag name="kernel.event_listener" event="kernel.exception" />
9092
</service>
9193
9294
.. code-block:: php
9395
9496
// app/config/config.php
9597
$container
96-
->register('kernel.listener.your_listener_name', 'AppBundle\EventListener\AcmeExceptionListener')
97-
->addTag('kernel.event_listener', array('event' => 'kernel.exception', 'method' => 'onKernelException'))
98+
->register('kernel.listener.your_listener_name', 'AppBundle\Listener\ExceptionListener')
99+
->addTag('kernel.event_listener', array('event' => 'kernel.exception'))
98100
;
99101
100102
.. note::
101103

102-
There is an additional tag option ``priority`` that is optional and defaults
103-
to 0. This value can be from -255 to 255, and the listeners will be executed
104-
in the order of their priority (highest to lowest). This is useful when
105-
you need to guarantee that one listener is executed before another.
104+
There is an optional tag option called ``method`` which defines which method
105+
to execute when the event is triggered. By default the name of the method is
106+
``on`` + "camel-cased event name". If the event is ``kernel.exception`` the
107+
method executed by default is ``onKernelException()``.
108+
109+
The other optional tag option is called ``priority`` and it defaults to ``0``.
110+
This value ranges from ``-255`` to ``255`` and it controls the order in which
111+
listeners are executed (the highest the priority, the earlier a listener is
112+
executed). This is useful when you need to guarantee that one listener is
113+
executed before another.
106114

107115
Creating an Event Subscriber
108116
----------------------------
109117

110-
Another way to listen to events is via an event subscriber. An event subscriber
111-
can define one or various methods that listen to one or various events,
112-
and can set a priority for each method. The higher the priority, the earlier
113-
the method is called. To learn more about event subscribers, see :doc:`/components/event_dispatcher/introduction`.
114-
The following example shows a subscriber that subscribes various methods
115-
to the ``kernel.exception`` event::
118+
Another way to listen to events is via an **event subscriber**, which is a class
119+
that can define one or more methods that listen to one or various events. The
120+
event priority can be defined for each method (the higher the priority, the earlier
121+
the method is called). To learn more about event subscribers, read :doc:`/components/event_dispatcher/introduction`.
122+
The following example shows an event subscriber that defines several methods which
123+
listen to the same ``kernel.exception`` event::
116124

117-
// src/AppBundle/EventListener/ExceptionSubscriber.php
118-
namespace AppBundle\EventSubscriber;
125+
// src/AppBundle/Subscriber/ExceptionSubscriber.php
126+
namespace AppBundle\Subscriber;
119127

120128
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
121129
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
@@ -126,45 +134,27 @@ to the ``kernel.exception`` event::
126134
{
127135
public static function getSubscribedEvents()
128136
{
129-
// Return the events it is subscribed to, the methods that listen each event and the
130-
// priority of each method
137+
// return the subscribed events, their methods and priorities
131138
return array(
132139
'kernel.exception' => array(
133-
array('onKernelExceptionPre', 10),
134-
array('onKernelExceptionMid', 5),
135-
array('onKernelExceptionPost', 0),
140+
array('processException', 10),
141+
array('logException', 0),
142+
array('notifyException', -10),
136143
)
137144
);
138145
}
139146

140-
public function onKernelExceptionPre(GetResponseForExceptionEvent $event)
147+
public function processException(GetResponseForExceptionEvent $event)
141148
{
142-
$exception = $event->getException();
143-
$message = sprintf(
144-
'My Error says: %s with code: %s',
145-
$exception->getMessage(),
146-
$exception->getCode()
147-
);
148-
149-
$response = new Response();
150-
$response->setContent($message);
151-
152-
if ($exception instanceof HttpExceptionInterface) {
153-
$response->setStatusCode($exception->getStatusCode());
154-
$response->headers->replace($exception->getHeaders());
155-
} else {
156-
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
157-
}
158-
159-
$event->setResponse($response);
149+
// ...
160150
}
161151

162-
public function onKernerlExceptionMid(GetResponseForExceptionEvent $event)
152+
public function logException(GetResponseForExceptionEvent $event)
163153
{
164154
// ...
165155
}
166156

167-
public function onKernerlExceptionPost(GetResponseForExceptionEvent $event)
157+
public function notifyException(GetResponseForExceptionEvent $event)
168158
{
169159
// ...
170160
}
@@ -180,7 +170,7 @@ is an event subscriber:
180170
# app/config/config.yml
181171
services:
182172
kernel.listener.your_subscriber_name:
183-
class: AppBundle\EventSubscriber\AcmeExceptionSubscriber
173+
class: AppBundle\Subscriber\ExceptionSubscriber
184174
tags:
185175
- { name: kernel.event_subscriber }
186176
@@ -192,7 +182,7 @@ is an event subscriber:
192182
193183
<services>
194184
<service id="acme_exception_subscriber"
195-
class="AppBundle\EventSubscriber\AcmeExceptionSubscriber">
185+
class="AppBundle\Subscriber\ExceptionSubscriber">
196186
197187
<tag name="kernel.event_subscriber"/>
198188
@@ -206,7 +196,7 @@ is an event subscriber:
206196
$container
207197
->register(
208198
'acme_exception_subscriber',
209-
'AppBundle\EventSubscriber\AcmeExceptionSubscriber'
199+
'AppBundle\Subscriber\ExceptionSubscriber'
210200
)
211201
->addTag('kernel.event_subscriber')
212202
;
@@ -223,13 +213,13 @@ sub-requests), which is why when working with the ``KernelEvents::REQUEST``
223213
event, you might need to check the type of the request. This can be easily
224214
done as follow::
225215

226-
// src/AppBundle/EventListener/AcmeRequestListener.php
227-
namespace AppBundle\EventListener;
216+
// src/AppBundle/Listener/RequestListener.php
217+
namespace AppBundle\Listener;
228218

229219
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
230220
use Symfony\Component\HttpKernel\HttpKernel;
231221

232-
class AcmeRequestListener
222+
class RequestListener
233223
{
234224
public function onKernelRequest(GetResponseEvent $event)
235225
{

0 commit comments

Comments
 (0)