PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 12 ■ ENTERPRISE PATTERNS

Page Controller


Much as I like the Front Controller pattern, it is not always the right approach to take. The investment in
up-front design tends to reward the larger system and penalize simple need-results-now projects. The
Page Controller pattern will probably be familiar to you already as it is a common strategy. Nevertheless,
it is worth exploring some of the issues.


The Problem


Once again, the problem is your need to manage the relationship among request, domain logic, and
presentation. This is pretty much a constant for enterprise projects. What differs, though, are the
constraints placed on you.
If you have a relatively simple project, and one where big up-front design could threaten your
deadline without adding huge amounts of value, Page Controller can be a good option for managing
requests and views.
Let’s say that you want to present a page that displays a list of all venues in the Woo system. Even
with the database retrieval code finished, without Front Controller already in place, I have a daunting
task to get just this simple result.
The view is a list of venues; the request is for a list of venues. Errors permitting, the request does not
lead to a new view, as you might expect in a complex task. The simplest thing that works here is to
associate the view and the controller—often in the same page.


Implementation


Although the practical reality of Page Controller projects can become fiendish, the pattern is simple.
Control is related to a view, or to a set of views. In the simplest case, this means that the control sits in
the view itself, although it can be abstracted, especially when a view is closely linked with others (that is
when you might need to forward to different pages in different circumstances).
Here is the simplest flavor of Page Controller:


<?php
require_once("woo/domain/Venue.php");
try {
$venues = \woo\domain\Venue::findAll();
} catch ( Exception $e ) {
include( 'error.php' );
exit(0);
}


// default page follows
?>




Venues


Venues


<?php foreach( $venues as $venue ) { ?>

Free download pdf