PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

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

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

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; A interface HttpKernelInterface { /** * @return Response A Response instance */ function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true); } A

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:

A // example.com/src/Framework.php A // ... A use Symfony\Component\HttpKernel\HttpKernelInterface; A class Framework implements HttpKernelInterface { // ... A public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { // ... } } A

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 A use Symfony\Component\HttpKernel\HttpCache\HttpCache; use Symfony\Component\HttpKernel\HttpCache\Store; A $framework = new Simplex\Framework($dispatcher, $matcher, $resolver); $framework = new HttpCache($framework, new Store(__DIR__.'/../cache')); A $framework-handle($request)-send(); A

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 A 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 8406 bytes)