PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Create your own framework... on top of the Symfony2 Components (part 11)

Note: This article was originally published at Planet PHP on 23 January 2012.
Planet PHP

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 have 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:

A // example.com/src/Simplex/Framework.php A namespace Simplex; A use Symfony\Component\HttpKernel\HttpKernel; A class Framework extends HttpKernel { } A

And the new front controller:

A // example.com/web/front.php A require_once __DIR__.'/../vendor/.composer/autoload.php'; A use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing; use Symfony\Component\HttpKernel; use Symfony\Component\EventDispatcher\EventDispatcher; A $request = Request::createFromGlobals(); $routes = include __DIR__.'/../src/app.php'; A $context = new Routing\RequestContext(); $matcher = new Routing\Matcher\UrlMatcher($routes, $context); $resolver = new HttpKernel\Controller\ControllerResolver(); A $dispatcher = new EventDispatcher(); $dispatcher-addSubscriber(new HttpKernel\EventListener\RouterListener($matcher)); A $framework = new Simplex\Framework($dispatcher, $resolver); A $response = $framework-handle($request); $response-send(); A

RouterListener is an implementation of the same logic we had in our framework: it matches the incoming request and populates the request attributes with route parameters.

Our code is now much more concise and surprisingly more robust and more powerful than ever. For instance, use the built-in ExceptionListener to make your error management configurable:

$errorHandler = function (HttpKernel\Exception\FlattenException $exception) { $msg = 'Something went wrong! ('.$exception-getMessage().')'; A return new Response($msg, $exception-

Truncated by Planet PHP, read more at the original (another 9464 bytes)