Skip to content

Added "How to create an event subscriber" #4538

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

Closed
wants to merge 14 commits into from
Closed
Changes from 10 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
125 changes: 120 additions & 5 deletions cookbook/service_container/event_listener.rst
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
.. index::
single: Events; Create listener
single: Create subscriber

How to Create an Event Listener
===============================
How to Create Event Listeners and Subscribers
=============================================

Symfony has various events and hooks that can be used to trigger custom
behavior in your application. Those events are thrown by the HttpKernel
component and can be viewed in the :class:`Symfony\\Component\\HttpKernel\\KernelEvents` class.

To hook into an event and add your own custom logic, you have to create
a service that will act as an event listener on that event. In this entry,
you will create a service that will act as an Exception Listener, allowing
a service that will act as an event listener on that event. You can do that in two different ways,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

service that will listen to that event.

creating an Event Listener or an Event Subscriber instead. In this entry,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here you use "Event Listener" and "Event Subscriber", but in the rest of the article it's "event listener" and "event subscriber". Is there any reason for the capitalization of letters in this case?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, there's no reason to do that, I'm going to fix it, thanks.

you will see the two ways of creating a service that will act as an Exception Listener, allowing
you to modify how exceptions are shown by your application. The ``KernelEvents::EXCEPTION``
event is just one of the core kernel events::
event is just one of the core kernel events.

Creating an Event Listener
--------------------------

The most common way to listen to an event is to register an event listener::

// src/Acme/DemoBundle/EventListener/AcmeExceptionListener.php
namespace Acme\DemoBundle\EventListener;
Expand Down Expand Up @@ -97,6 +104,112 @@ using a special "tag":
in the order of their priority (highest to lowest). This is useful when
you need to guarantee that one listener is executed before another.

Creating an Event Subscriber
----------------------------

Another way to listen to events is via an event subscriber. An event subscriber
can define one or various method that listen to one or various events,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo: "one or various methods that listen"

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I'll fix it

and can set a priority for each method. To learn more about event subscribers,
see `The EventDispatcher component`_. The following example shows a subscriber
that subscribes various methods to the kernel.exception event::
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Syntax error: It should be kernel.exception instead of kernel.exception, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes


// src/Acme/DemoBundle/EventListener/ExceptionSubscriber.php
namespace Acme\DemoBundle\EventSubscriber;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about using the new AppBundle?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I'll change it


use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

class ExceptionSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
// Return the events it is subscribed to, the methods that listen each event and the
// priority of each method
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe we could also add a minor note about priority: ... priority of each method (the higher, the more priority)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't do that because there is already a note about priority in the event listener above, and I thought that it's obvious, but if you think thats it's necessary I can do it.

return array(
'kernel.exception' => array(
array('onKernelExceptionPre', 10),
array('onKernelExceptionMid', 5),
array('onKernelExceptionPost', 0),
)
);
}

public function onKernelExceptionPre(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand why we show the code of this method and not the other ones.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's because I only wanted to show how to define an event subscriber, and so, show that in an event subscriber we can define various methods that listen to the same event, but I thought that the code of the method wasn't relevant for the example. I added the code of one method to show the similarity between the method in the event listener and the same functionality in the event subscriber one. Therefore, I can remove the code of the method or add some sample code to the other ones.

Which do you think is the best option?

$message = sprintf(
'My Error says: %s with code: %s',
$exception->getMessage(),
$exception->getCode()
);

$response = new Response();
$response->setContent($message);

if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}

$event->setResponse($response);
}

public function onKernerlExceptionMid(GetResponseForExceptionEvent $event)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method name sounds a bit weird to me.

{
// ...
}

public function onKernerlExceptionPost(GetResponseForExceptionEvent $event)
{
// ...
}
}

Now, you just need to register the class as a service and notify Symfony that it
is an event subscriber:

.. configuration-block::

.. code-block:: yaml

# app/config/config.yml
services:
kernel.listener.your_subscriber_name:
class: Acme\DemoBundle\EventSubscriber\AcmeExceptionSubscriber
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You used an AppBundle and an EventSubscriber class above which should be reused here then.

tags:
- { name: kernel.event_subscriber }

.. code-block:: xml

<!-- app/config/config.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services">

<services>
<service id="acme_exception_subscriber"
class="Acme\DemoBundle\EventSubscriber\AcmeExceptionSubscriber">

<tag name="kernel.event_subscriber"/>

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need for this blank line

</service>
</services>
</container>

.. code-block:: php

// app/config/config.php
$container
->register(
'acme_exception_subscriber',
'Acme\DemoBundle\EventSubscriber\AcmeExceptionSubscriber'
)
->addTag('kernel.event_subscriber')
;

Request Events, Checking Types
------------------------------

Expand Down Expand Up @@ -133,3 +246,5 @@ done as follow::
Two types of request are available in the :class:`Symfony\\Component\\HttpKernel\\HttpKernelInterface`
interface: ``HttpKernelInterface::MASTER_REQUEST`` and
``HttpKernelInterface::SUB_REQUEST``.

.. _`The EventDispatcher component`: http://symfony.com/doc/current/components/event_dispatcher/index.html