Recent changes RSS feed
 

Template Method Pattern

The Template Method Pattern 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

<?php
// Super class
class Page {
   // Template method
   function header() {
       $html = <<<EOD
<html>
<head>
<title>TemplateMethod.com</title>
</head>
<body>
EOD;
        return $html;
   }
   // Template method
   function footer() {
       $html = <<<EOD
<p>&copy; TemplateMethod Inc. 2003</p>
</body>
</html>
EOD;
        return $html;
   }
   // Template method
   function body() {
       // Do nothing
   }
}
 
class Login extends Page {
   // Template method
   function body() {
       $html = <<<EOD
<form action="login.php" method="post">
<input type="text" name="username"><br>
<input type="password" name="password"><br>
<input type="submit" name="login" value="Login">
</form>
EOD;
       return $html;
   }
}
 
class News extends Page {
   // Template method
   function header() {
       $html = <<<EOD
<html>
<head>
<title>TemplateMethod.com - Latest News</title>
</head>
<body>
EOD;
        return $html;
   }
 
   // Template method
   function body() {
        $html = <<<EOD
<h1>Latest News</h1>
<!-- Display database query results here perhaps -->
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 Pattern 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

 
pattern/template_method.txt · Last modified: 2006/12/09 17:14
 
Hosting for this site donated by Procata PHP Development