This article is part of a series of articles that explains how to create a framework with the Symfony2 Components: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12.
If you were to use our framework right now, you would probably have to add support for custom error messages. Right now, we have 404 and 500 error support but the responses are hardcoded in the framework itself. Making them customizable is easy enough though: dispatch a new event and listen to it. Doing it right means that the listener has to call a regular controller. But what if the error controller throws an exception? You will end up in an infinite loop. There should be an easier way, right?
Enter the HttpKernel class. Instead of solving the same problem over and
over again and instead of reinventing the wheel each time, the HttpKernel
class is a generic, extensible, and flexible implementation of
HttpKernelInterface.
This class is very similar to the framework class we have written so far: it dispatches events at some strategic points during the handling of the request, it uses a controller resolver to choose the controller to dispatch the request to, and as an added bonus, it takes care of edge cases and provides great feedback when a problem arises.
Here is the new framework code:
<?php // example.com/src/Simplex/Framework.php namespace Simplex; use Symfony\Component [HttpKernel\HttpKernel;] class Framework extends [HttpKernel] { }
And the new front controller:
<?php // example.com/web/front.php require_once __DIR__.'/../vendor/.composer/autoload.php'; use Symfony\Component [HttpFoundation\Request;] use Symfony\Component [HttpFoundation\Response;] use Symfony\Component\Routing; use Symfony\Component [HttpKernel;] use Symfony\Component\EventDispatcher\EventDispatcher; $request = Request::createFromGlobals(); $routes = include __DIR__.'/../src/app.php'; $context = new Routing\RequestContext(); $matcher = new Routing\Matcher\UrlMatcher($routes, $context); $resolver = new [HttpKernel\Controller\ControllerResolver();] $dispatcher = new EventDispatcher(); $dispatcher->addSubscriber(new [HttpKernel\EventListener\RouterListener(] matcher));
Truncated by Planet PHP, read more at the original (another 11484 bytes)