Command Pattern

A GoF Design Pattern with the intent: “Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.”

In WACT, this is seen with the FormController, where users can define a class which must contain the method performAction();

class AddressForm extends PostFormController {
 
    // Code omitted
 
    function InitializeActions() {
        $this->registerSubmitAction("register", "RegisterUser", PRE_VALID);
        $this->registerDefaultSubmitAction("RegisterUser", PRE_VALID);
    }
 
    // Code omitted
}

The registerSubmitAction call above points the controller at the class RegisterUser, which is where the Command pattern resides.

class RegisterUser {
 
    function performAction(&$context) {
        $DataSpace =& $context->getDataSpace();
        $Page =& new Template('/input/thanks.html');
        $Page->import($DataSpace->export());
        $Page->display();
        return FORM_COMPLETE;
    }
 
}

The FormController expects to find the performAction method in the Action Class RegisterUser, calling it when the form is submitted (and successfully validated).

The Command pattern is a Gang of Four Design Pattern, used to allow a function name to be wrapped up in a class namespace, so that some code, which will call the function, can be given an instance of one of many classes without caring which which instance it’s dealing with.

A possible (somewhat stupid) PHP example might be;

<?php
/* interface */ class Tag {
   // The abstract command method
   function render($content);
}
 
class Bold {
   function render($content) {
       return "<b>$content</b>";
   }
}
 
class Italic {
   function render($content) {
       return "<i>$content</i>";
   }
}
 
$commands = array (
    new Bold(),new Italic(), new Italic(), new Bold()
);
 
// Iterate over the command objects
foreach ( $commands as $command ) {
    echo ( $command->render('Hello World!') );
}
?>

The Command pattern is used widely on in web based application frameworks like Java Struts from a PHP Perspective, usually in Action Classes, to allow framework users to define logic which responds to “events” in the application. Action Classes can be regarded as the “verbs” of the framework - they act on things - they do things.

Additional Information