News Archive
PhpRiot Newsletter
Your Email Address:

More information

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

Note: This article was originally published at Planet PHP on 16 April 9640.
Planet PHP

You might think that our framework is already pretty solid and you are probably right. But let's see how we can improve it nonetheless.

Right now, all our examples use procedural code, but remember that controllers can be any valid PHP callbacks. Let's convert our controller to a proper class:

class LeapYearController { public function indexAction($request) { if (is_leap_year($request-attributes-get('year'))) { return new Response('Yep, this is a leap year!'); } A return new Response('Nope, this is not a leap year.'); } } A

Update the route definition accordingly:

$routes-add('leap_year', new Routing\Route('/is_leap_year/{year}', array('year' = null, '_controller' = array(new LeapYearController(), 'indexAction'),))); A

The move is pretty straightforward and makes a lot of sense as soon as you create more pages but you might have noticed a non-desirable side-effect... The LeapYearController class is always instantiated, even if the requested URL does not match the leap_year route. This is bad for one main reason: performance wise, all controllers for all routes must now be instantiated for every request. It would be better if controllers were lazy-loaded so that only the controller associated with the matched route is instantiated.

To solve this issue, and a bunch more, let's install and use the HttpKernel component:

{ "require": { "symfony/class-loader": "2.1.*", "symfony/http-foundation": "2.1.*", "symfony/routing": "2.1.*", "symfony/http-kernel": "2.1.*" } } A

The HttpKernel component has many interesting features, but the one we need right now is the controller resolver. A controller resolver knows how to determine the controller to execute and the arguments to pass to it, based on a Request object. All controller resolvers implement the following interface:

namespace Symfony\Component\HttpKernel\Controller; A interface ControllerResolverInterface { function getController(Request $request); A function getArguments(Request $request, $controller); } A

The getController() method relies on the same convention as the one we have defined earlier: the _controller request attribute must contain the controller associated with the Request. Besides the built-in PHP callbacks, getController() also supports strings composed of a class name fo

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