January 13, 2012

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!');
}
return new Response('Nope, this is not a leap year.');
}
}

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:

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:

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 followed by
two colons and a method name as a valid callback, like 'class::method':

Finally, you can also define default values for any argument that matches an
optional attribute of the Request:

public function indexAction($year = 2012)

Let's just inject the $year request attribute for our controller:

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

The controller resolver also takes care of validating the controller callable
and its arguments. In case of a problem, it throws an exception with a nice
message explaining the problem (the controller class does not exist, the
method is not defined, an argument has no matching attribute, ...).

With the great flexibility of the default controller resolver, you might
wonder why someone would want to create another one (why would there be an
interface if not). Two examples: in Symfony2, getController() is enhanced to
support controllers as services; and in FrameworkExtraBundle,
getArguments() is enhanced to support parameter converters, where request
attributes are converted to objects automatically.