PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 11 ■ PERFORMING AND REPRESENTING TASKS

}


function getContext() {
return $this->context;
}


function process() {
$cmd = CommandFactory::getCommand( $this->context->get('action') );
if (! $cmd->execute( $this->context ) ) {
// handle failure
} else {
// success
// dispatch view now..
}
}
}


$controller = new Controller();
// fake user request
$context = $controller->getContext();
$context->addParam('action', 'login' );
$context->addParam('username', 'bob' );
$context->addParam('pass', 'tiddles' );
$controller->process();


Before I call Controller::process(), I fake a web request by setting parameters on the
CommandContext object instantiated in the controller’s constructor. The process() method delegates
object instantiation to the CommandFactory object. It then invokes execute() on the returned command.
Notice how the controller has no idea about the command’s internals. It is this independence from the
details of command execution that makes it possible for you to add new Command classes with a relatively
small impact on this framework.
Here's one more Command class:


class FeedbackCommand extends Command {


function execute( CommandContext $context ) {
$msgSystem = Registry::getMessageSystem();
$email = $context->get( 'email' );
$msg = $context->get( 'msg' );
$topic = $context->get( 'topic' );
$result = $msgSystem->send( $email, $msg, $topic );
if (! $result ) {
$context->setError( $msgSystem->getError() );
return false;
}
return true;
}
}

Free download pdf