Symfony 4 was released on November 30th.
Update now to the best Symfony ever!

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

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 ⚔'));
        }

        // ...
    }
}

Comments

I like this idea, it makes me wonder whether the EventDispatcher and HttpKernel are (or will be) compatible with the famous "middleware" pattern used by many JS frameworks, this would be a nice advance in PHP frameworks 👍
@Alex Rock Ancelet: Something like http://stackphp.com/middlewares/ perhaps? :)
Booya! I've wanted this for ages actually... it was one of the things I didn't get done for the MicroKernelTrait :). Btw, the MicroKernelTrait is automatically used for Symfony 4 Flex projects... so *all* you need to do is add the EventSubscriberInterface :).
The Legend of Zelda: best game ever!
The first one, of course.

Nb: nice feature
@Maxime Steinhausser: Or https://laravel.com/docs/5.5/middleware even?

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.