PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 12 ■ ENTERPRISE PATTERNS

}


function getRequest() {
return $this->request;
}
}


This class uses some of the tools that you have already looked at, in particular the Request and
RequestRegistry classes. The PageController class’s main roles are to provide access to a Request object
and to manage the including of views. This list of purposes would quickly grow in a real project as more
child classes discover a need for common functionality.
A child class could live inside the view, and thereby display it by default as before, or it could stand
separate from the view. The latter approach is cleaner, I think, so that’s the path I take. Here is a
PageController that attempts to add a new venue to the system:


namespace woo\controller;
//...


class AddVenueController extends PageController {
function process() {
try {
$request = $this->getRequest();
$name = $request->getProperty( 'venue_name' );
if ( is_null( $request->getProperty('submitted') ) ) {
$request->addFeedback("choose a name for the venue");
$this->forward( 'add_venue.php' );
} else if ( is_null( $name ) ) {
$request->addFeedback("name is a required field");
$this->forward( 'add_venue.php' );
}


// just creating the object is enough to add it
// to the database
$venue = new \woo\domain\Venue( null, $name );
$this->forward( "ListVenues.php" );
} catch ( Exception $e ) {
$this->forward( 'error.php' );
}
}
}


$controller = new AddVenueController();
$controller->process();


The AddVenueController class only implements the process() method. process() is responsible for
checking the user’s submission. If the user has not submitted a form, or has completed the form
incorrectly, the default view (add_venue.php) is included, providing feedback and presenting the form. If
I successfully add a new user, then the method invokes forward() to send the user to the ListVenues
page controller.
Note the format I used for the view. I tend to differentiate view files from class files by using all
lowercase file names in the former and camel case (running words together and using capital letters to
show the boundaries) in the latter.

Free download pdf