In the conclusion of the second part of this series, I've talked about one
great benefit of using the Symfony2 components: the interoperability between
all frameworks and applications using them. Let's do a big step towards this
goal by making our framework implement HttpKernelInterface:
namespace Symfony\Component [HttpKernel;] interface [HttpKernelInterface] { /** * @return Response A Response instance */ function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true); }
HttpKernelInterface is probably the most important piece of code in the [HttpKernel] component, no kidding. Frameworks and applications that implement
this interface are fully interoperable. Moreover, a lot of great features will
come with it for free.
Update your framework so that it implements this interface:
<?php // example.com/src/Framework.php // ... use Symfony\Component [HttpKernel\HttpKernelInterface;] class Framework implements [HttpKernelInterface] { // ... public function handle(Request $request, $type = [HttpKernelInterface::MASTER_REQUEST,] $catch = true) { // ... } }
Even if this change looks trivial, it brings us a lot! Let's talk about one of the most impressive one: transparent HTTP caching support.
The HttpCache class implements a fully-featured reverse proxy, written in
PHP; it implements HttpKernelInterface and wraps another
HttpKernelInterface instance:
// example.com/web/front.php use Symfony\Component [HttpKernel\HttpCache\HttpCache;] use Symfony\Component [HttpKernel\HttpCache\Store;] $framework = new Simplex\Framework($dispatcher, $matcher, $resolver); $framework = new [HttpCache(] framework, new Store(__DIR__.'/../cache')); $framework->handle($request)->send();
That's all it takes to add HTTP caching support to our framework. Isn't it amazing?
Configuring the cache needs to be done via HTTP cache headers. For instance,
to cache a response for 10 seconds, use the Response::setTtl() method::
// example.com/src/Calendar/Controller/LeapYearController.php
public function indexAction(Request $request, $year)
{
$leapyear = new LeapYear();
if ($leapyear->isLeapYear($year)) {
$response = new Response('Yep, this is a leap year!');
} else {
$response = new Response"/>Truncated by Planet PHP, read more at the original (another 8450 bytes)