PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 12 ■ ENTERPRISE PATTERNS

);


private $status = 0;


final function __construct() { }


function execute( \woo\controller\Request $request ) {
$this->status = $this->doExecute( $request );
$request->setCommand( $this );
}


function getStatus() {
return $this->status;
}


static function statuses( $str='CMD_DEFAULT' ) {
if ( empty( $str ) ) { $str = 'CMD_DEFAULT'; }
// convert string into a status number
return self::$STATUS_STRINGS[$str];
}
abstract function doExecute( \woo\controller\Request $request );


}


The Command class defines an array of status strings (severely cut for the sake of this example). It
provides the statuses() method for converting a string ("CMD_OK") to its equivalent number, and
getStatus() for revealing the current Command object’s status flag. If you want to be strict, statuses()
could throw an exception on failure. As it is, the method returns null by default if the right element is
not defined. The execute() method uses the return value of the abstract doExecute() to set the status
flag, and to cache itself in the Request object.


A Concrete Command


Here is how a simple AddVenue command might look:


namespace woo\command;
//...


class AddVenue extends Command {


function doExecute( \woo\controller\Request $request ) {
$name = $request->getProperty("venue_name");
if (! $name ) {
$request->addFeedback( "no name provided" );
return self::statuses('CMD_INSUFFICIENT_DATA');
} else {
$venue_obj = new \woo\domain\Venue( null, $name );
$request->setObject( 'venue', $venue_obj );
$request->addFeedback( "'$name' added ({$venue_obj->getId()})" );
return self::statuses('CMD_OK');
}


}
}

Free download pdf