The most basic presentation pattern is probably that old standby, the Model View Controller (MVC). Rather than re-hash MVC, which has already been covered elsewhere, I figured I’d jump ahead to something a bit more interesting: the Front Controller.

Presentation patterns in general are designed to promote the independent operation of the business logic (model) and presentation (view) tiers of a system. The controller is responsible for coordinating the operations of the other two layers by taking user input, manipulating the model, and causing the view to react appropriately. The Front Controller pattern goes a step further by exposing a single entry point to your system, and delegating incoming requests to objects that implement the proper behavior.

The Problem

When a request enters your system, you must interpret it, invoke any relevant business logic, and return a response. For a simple web application this is all done in a single script, inside the view itself. As a system grows, however, managing these three responsibilities in a single monolithic file becomes increasingly difficult.

When multiple requests require common actions (authentication, logging, configuration, etc.), you may find yourself copying and pasting code, which makes your system significantly less maintainable. If you decide to change something in the future, it’s very easy for your system to become inconsistent.

The Front Controller pattern consolidates a web application so that it has a single point of entry for all incoming requests. It defines a single class that is responsible for setting up requests, and invoking the appropriate business logic. Moreover, you can consolidate common code like authentication and logging by simply extending your Front Controller.

Implementation

The Front Controller pattern typically consists of two parts:

  1. The handler is an object that defines a single point of entry for your system, and receives incoming requests from the web server.
  2. The command hierarchy is a set of classes that are responsible for actually performing whatever behavior is required to respond to a particular request.

Upon receiving an incoming request, the handler extracts enough information to determine the action that should be performed, then dispatches the request to a command, which actually carries out that action.

The handler can determine which command to invoke in a couple of ways. You could have a configuration file that maps a part of the URL to a command, or you can simply take a piece of the URL and use it to dynamically instantiate a command class (i.e. you pass the name of the command class you want to invoke as a query string parameter). I’ll be taking the latter, simpler approach. Don’t worry if it doesn’t make sense yet, it will.

We’ll begin with a simple handler,

class Controller {
  public static function Run() {
    $command = self::getCommand($_GET['command']);
    $command->execute($_GET);
  }

  public static function getCommand( $command ) {
    $commandClass = ucfirst($command) . 'Command';
    $commandFile  = $commandClass . '.php';

    if(file_exists($commandFile)) {
      include($commandFile);

      if(class_exists($commandClass)) {
        return new $commandClass();
      }
    }

    include('Error404Command.php');
    return new Error404Command();
  }
}

The logic is fairly simple. The handler tries to instantiate a class by concatenating the command name (passed in the query string variable ‘command’) and “Command.” It then invokes the Command::execute() method, passing the $_GET superglobal as a parameter. In a real application, I would encapsulate the $_GET and $_POST superglobals, probably using the Registry pattern. If the controller can’t find the implementation file for the command class, or the command class doesn’t exist, it executes a special command that returns a basic error message.

The command hierarchy is made up of a set of classes that inherit from the Command class.

abstract class Command {
  final function __construct() { }

  final function execute( $request ) {
    $this->doExecute( $request );
  }

  abstract function doExecute( $request );
}

The abstract command class defines an execute() method which simply delegates to doExecute(). Concrete subclasses that inherit from Command implement the doExecute() method, where the command’s behavior is defined.

Finally, a concrete command class executes the behavior necessary to respond to the request, and includes the appropriate view.

class HelloCommand extends Command {
  public function doExecute( $request ) {
    $name = $request['name'];
    if(!$name) {
      $name = 'Anonymous';
    }
    $hits = $this->hit();
    include('HelloView.php');
  }

  public function hit( ) {
    $file = 'hits.txt';

    $hits = file_get_contents($file);
    $hits++;
    file_put_contents($file, $hits);

    return $hits;
  }
}

Some simple logic that doesn’t belong in the view is included in order to demonstrate the sorts of things you might include in your Command. Again, in a non-trivial application there would be additional layers that would encapsulate data access and request processing, but for this example I’ve simplified things.

Try it out!

The HelloCommand simply displays a greeting, and shows how many people have viewed the page. To try it out enter your name in the form to the right and press submit.

To kick things off (in your index.php file, for example) you’ll need to execute the following code:

include('Controller.php');
include('Command.php');

Controller::Run();

Consequences

For languages like PHP that encourage a store nothing architecture, developers sometimes shy away from the Front Controller pattern because they feel that the setup and tear-down of the Front Controller infrastructure is too costly. But, as evidenced by the 50 or so lines of code on this page, the Front Controller doesn’t necessarily require elaborate infrastructure to be useful.

That said, the Front Controller is definitely a more complicated design than a simple MVC architecture, let alone a single script. But once you’re familiar with it, this pattern is quite intuitive and allows you to rapidly add features to a web application without a lot of redundant coding. Since the handler exposes a single point of entry for your application, it’s easy to enhance it with a Decorator or Filter Chain. I’ll be discussing these patterns in the future, so be sure to subscribe to my feed if you’re interested.

You can grab the code from this post here.

Update: I got bored and decided the page wasn’t colorful (or web 2.0) enough. Now it uses CSS to make awesome web 2.0 color schemes (randomly selected, in the command object). You can grab the new version here. Use this version if you’re planning on using this code in production, as it contains an important security fix (see comments for more details).