PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 10 ■ PATTERNS FOR FLEXIBLE OBJECT PROGRAMMING


class LogRequest extends DecorateProcess {
function process( RequestHelper $req ) {
print CLASS.": logging request\n";
$this->processrequest->process( $req );
}
}


class AuthenticateRequest extends DecorateProcess {
function process( RequestHelper $req ) {
print CLASS.": authenticating request\n";
$this->processrequest->process( $req );
}
}


class StructureRequest extends DecorateProcess {
function process( RequestHelper $req ) {
print CLASS.": structuring request data\n";
$this->processrequest->process( $req );
}
}


Each process() method outputs a message before calling the referenced ProcessRequest object’s
own process() method. You can now combine objects instantiated from these classes at runtime to
build filters that perform different actions on a request, and in different orders. Here’s some code to
combine objects from all these concrete classes into a single filter:


$process = new AuthenticateRequest( new StructureRequest(
new LogRequest (
new MainProcess()
)));
$process->process( new RequestHelper() );


This code will give the following output:

Authenticate
Request: authenticating request
StructureRequest: structuring request data
LogRequest: logging request
MainProcess: doing something useful with request


■Note This example is, in fact, also an instance of an enterprise pattern called Intercepting Filter. Intercepting


Filter is described in Core J2EE Patterns.

Free download pdf