sajad torkamani

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.

Symfony: How does the HttpKernel work?

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

// trigger the kernel.terminate event
$kernel->terminate($request, $response);

The steps for using HttpKernel are roughly as follows:

  1. Create an event dispatcher
  2. Create controller resolver
  3. Create argument resolver
  4. Instantiate the kernel with the event dispatcher, controller resolver, and argument resolver
  5. Execute the kernel with HttpKernel::handle(). This will dispatch various events that resolve a controller and return a response.
  6. Send the headers and content using the response.
  7. Trigger the kerner.terminate event.


Tagged: Symfony