New in Symfony 3.4: Subscribing to events in the micro kernel
September 20, 2017 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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 ⚔'));
}
// ...
}
}
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
The first one, of course.
Nb: nice feature