Symfony: How does the HttpKernel work?
20 November 2022 (Updated 20 November 2022)
On this page
In a nutshell
The HttpKernel component provides a structured process for converting an incoming HTTP request (encapsulated as a Request
object) into a response (encapsulated as a Response
object) using the EventDispatcher component.
The HttpKernel is driven by events
The HttpKernel::handle()
method works internally by dispatching various events. This makes it flexible but also abstract because all the work of a framework/application using HttpKernel is done in event listeners.
Here’s an example application that uses HttpKernel
:
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\HttpKernel;
// create the Request object
$request = Request::createFromGlobals();
$dispatcher = new EventDispatcher();
// ... add some event listeners
// create your controller and argument resolvers
$controllerResolver = new ControllerResolver();
$argumentResolver = new ArgumentResolver();
// instantiate the kernel
$kernel = new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver);
// actually execute the kernel, which turns the request into a response
// by dispatching events, calling a controller, and returning the response
$response = $kernel->handle($request);
// send the headers and echo the content
$response->send();
// trigger the kernel.terminate event
$kernel->terminate($request, $response);
The steps for using HttpKernel
are roughly as follows:
- Create an event dispatcher
- Create controller resolver
- Create argument resolver
- Instantiate the kernel with the event dispatcher, controller resolver, and argument resolver
- Execute the kernel with
HttpKernel::handle()
. This will dispatch various events that resolve a controller and return a response. - Send the headers and content using the response.
- Trigger the
kerner.terminate
event.
Sources
Tagged:
Symfony
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment