====== 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; $content"; } } class Italic { function render($content) { return "$content"; } } $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]], 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 ===== * [[http://c2.com/cgi/wiki?CommandPattern|C2 Wiki on the Command Pattern]] * [[http://jamesthornton.com/eckel/TIPython/html/Sect09.htm|Bruce Eckel - Thinking in Python on the Command Pattern]] * [[http://phrame.sourceforge.net/docs/guide/controller.php#action_classes|Phrame Docs on Action Classes]] - note the Phrame implementation is fairly different to WACT, the ActionClass being the place to deal with form validation, which WACT handles this in the FormController.