PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 12 ■ ENTERPRISE PATTERNS

As you can see, most of this class is taken up with mechanisms for setting and acquiring properties.
The init() method is responsible for populating the private $properties array. Notice that it works with
command line arguments as well as the HTTP requests. This is extremely useful when it comes to testing
and debugging.
Once you have a Request object, you should be able to access an HTTP parameter via the
getProperty() method, which accepts a key string and returns the corresponding value (as stored in the
$properties array). You can also add data via setProperty().
The class also manages a $feedback array. This is a simple conduit through which controller classes
can pass messages to the user.


A Command


You have already seen the Command base class, and Chapter 11 covered the Command pattern in detail, so
there’s no need to go too deep into Commands. Let’s round things off, though, with a simple concrete
Command object:


namespace woo\command;
//...


class DefaultCommand extends Command {
function doExecute( \woo\controller\Request $request ) {
$request->addFeedback( "Welcome to WOO" );
include( "woo/view/main.php");
}
}


This is the Command object that is served up by CommandResolver if no explicit request for a particular
Command is received.
As you may have noticed, the abstract base class implements execute() itself, calling down to the
doExecute() implementation of its child class. This allows us to add setup and cleanup code to all
commands simply by altering the base class.
The execute() method is passed a Request object that gives access to user input, as well as to the
setFeedback() method. DefaultCommand makes use of this to set a welcome message.
Finally, the command dispatches control to a view, simply by calling include(). Embedding the
map from command to view in the Command classes is the simplest dispatch mechanism, but for small
systems, it can be perfectly adequate. A more flexible strategy can be seen in the “Application
Controller” section.
The file main.php contains some HTML and a call into the Request object to check for any feedback
(I’ll cover views in more detail shortly). I now have all the components in place to run the system. Here’s
what I see:




Woo! it's Woo!







Welcome to WOO
Free download pdf