CHAPTER 12 ■ ENTERPRISE PATTERNS
function init() {
$applicationHelper
= ApplicationHelper::instance();
$applicationHelper->init();
}
function handleRequest() {
$request = new \woo\controller\Request();
$cmd_r = new \woo\command\CommandResolver();
$cmd = $cmd_r->getCommand( $request );
$cmd->execute( $request );
}
}
Simplified as this is, and bereft of error handling, there isn’t much more to the Controller class. A
controller sits at the tip of a system delegating to other classes. It is these other classes that do most of
the work.
run() is merely a convenience method that calls init() and handleRequest(). It is static, and the
constructor is private, so the only option for client code is to kick off execution of the system. I usually do
this in a file called index.php that contains only a couple of lines of code:
require( "woo/controller/Controller.php" );
\woo\controller\Controller::run();
The distinction between the init() and handleRequest() methods is really one of category in PHP.
In some languages, init() would be run only at application startup, and handleRequest() or equivalent
would be run for each user request. This class observes the same distinction between setup and request
handling, even though init() is called for each request.
The init() method obtains an instance of a class called ApplicationHelper. This class manages
configuration data for the application as a whole. init() calls a method in ApplicationHelper, also
called init(), which, as you will see, initializes data used by the application.
The handleRequest() method uses a CommandResolver to acquire a Command object, which it runs by
calling Command::execute().
ApplicationHelper
The ApplicationHelper class is not essential to Front Controller. Most implementations must acquire
basic configuration data, though, so I should develop a strategy for this. Here is a simple
ApplicationHelper:
namespace woo\controller;
//...
class ApplicationHelper {
private static $instance;
private $config = "/tmp/data/woo_options.xml";
private function __construct() {}
static function instance() {
if (! self::$instance ) {
self::$instance = new self();
}