PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 12 ■ ENTERPRISE PATTERNS


This level of hard-coding is fine, as long as the commands will always be used in the same way. It
begins to break down, though, if I want a special view for AddVenue in some circumstances, and if I want
to alter the logic by which one command leads to another (perhaps one flow might include an additional
screen between a successful venue addition and the start of a space addition). If each of your commands
is only used once, in one relationship to other commands, and with one view, then you should hard-
code your commands’ relationship with each other and their views. Otherwise, you should read on.
An application controller class can take over this logic, freeing up Command classes to concentrate on
their job, which is to process input, invoke application logic, and handle any results.


Implementation


As always, the key to this pattern is the interface. An application controller is a class (or a set of classes)
that the front controller can use to acquire commands based on a user request and to find the right view
to present after the command has been run. You can see the bare bones of this relationship in Figure 12–
6.
As with all patterns in this chapter, the aim is to make things as simple as possible for the client
code—hence the spartan front controller class. Behind the interface, though, I must deploy an
implementation. The approach laid out here is just one way of doing it. As you work through this section,
remember that the essence of the pattern lies in the way that the participants, the application controller,
the commands, and the views, interact, and not with the specifics of this implementation.
Let’s begin with the code that uses the application controller.


Figure 12–6. The Application Controller pattern


The Front Controller


Here is how the FrontController might work with the AppController class (simplified and stripped of
error handling):


function handleRequest() {
$request = new Request();
$app_c = \woo\base\ApplicationRegistry::appController();


while( $cmd = $app_c->getCommand( $request ) ) {
$cmd->execute( $request );

Free download pdf