Symfony News

New in Symfony 3.4: Subscribing to events in the micro kernel

Maxime Steinhausser

Contributed by
Maxime Steinhausser
in #23812.

In Symfony 2.8, we introduced the MicroKernel trait to provide a different and simpler way to configure the Symfony full-stack framework. Symfony 4, to be released in November 2017, will use this trait by default when creating new applications.

Meanwhile, in Symfony 3.4 we improved the micro kernel to allow subscribing to events. You just need to implement the usual EventSubscriberInterface and add the methods handling the different events.

Consider a simple application that wants to handle the exceptions occurred during its execution. In Symfony 3.4 you can make the micro kernel listen to the KernelEvents::EXCEPTION event and implement the exception handling logic in a method of the kernel:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/Kernel.php
namespace App;

use App\Exception\DangerException;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\HttpKernel\KernelEvents;

class Kernel extends BaseKernel implements EventSubscriberInterface
{
    use MicroKernelTrait;

    // ...

    public static function getSubscribedEvents()
    {
        return [KernelEvents::EXCEPTION => 'handleExceptions'];
    }

    public function handleExceptions(GetResponseForExceptionEvent $event)
    {
        if ($event->getException() instanceof DangerException) {
            $event->setResponse(Response::create('It\'s dangerous to go alone. Take this ⚔'));
        }

        // ...
    }
}

Be trained by Symfony experts - 2017-09-25 Cologne - 2017-09-25 Paris - 2017-09-25 Paris


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook