====== Template Method Pattern ====== The [[Template Method]] is a [[Gang Of Four]] pattern which could also be described as the frameworkers pattern: essentially it's an application of polymorphism. The general approach of the template method is to define a set of general class methods which subclasses can (perhaps optionally) override the template method with a different implementation. This then allows either the superclass or some other class to be given any object containing the template method(s) and execute it, producing varying output. ===== Example ===== TemplateMethod.com EOD; return $html; } // Template method function footer() { $html = <<© TemplateMethod Inc. 2003

EOD; return $html; } // Template method function body() { // Do nothing } } class Login extends Page { // Template method function body() { $html = <<

EOD; return $html; } } class News extends Page { // Template method function header() { $html = << TemplateMethod.com - Latest News EOD; return $html; } // Template method function body() { $html = <<Latest News EOD; return $html; } } class PageWriter { var $page; function PageWriter($page) { $this->page = $page; } function render() { $html = $this->page->header(); $html .= $this->page->body(); $html .= $this->page->footer(); return $html; } } switch ( strtolower(@$_GET['page']) ) { case 'login': $page = new Login(); break; case 'news': $page = new News(); break; default: trigger_error('Invalid page',E_USER_ERROR); break; } $pageWriter = new PageWriter($page); echo ( $pageWriter->render() ); ?>
===== WACT implementation ===== The [[Template Method]] is used extensively in the WACT [[wact:Template Component Architecture]], allowing customizable tag components to be defined at compile time, which write specific code into the compiled template. ===== Additional Information ===== * WACT [[wact:Template Component Architecture]] * [[http://jamesthornton.com/eckel/TIPython/html/Sect04.htm|Bruce Eckel in Thinking in Python]] - demonstrates the framework concept with a [[Template Method]] * [[http://www.zend.com/zend/php5/php5-OOP.php|The Template Method Pattern in PHP 5]]