When you design a complex application, it’s always useful to separate the presentation layer from the business logic. Usually, when dealing with web apps, this involves handing templates which are “filled” with data by your controller.
The common rationale is that the template should contain as little logic as possible and that it should be easily editable by non-programmers.
There are several PHP packages (Smarty, PHPTal, etc…) that aim at providing a flexible and neat template framework. They usually try to force you not to put code in the template by providing a limited set of directives that can be used, such as placeholders, foreach-style control blocks, conditional blocks… but in the end, every framework I’ve seen also includes a directive that allows you to put arbitrary PHP code inside the template.
Thus I’ve always wondered: what’s the point? Why don’t you just use PHP as a templating engine instead of inventing a new language? 😉
So, let me introduce my super-duper template class!
* Copyright ©2007-2008 by Simone Tellini
private static $commonVars = array();
public function __construct( $template )
$this->tpl = $template;
$this->vars = self::$commonVars;
// you might set some variables before instantiating your templates when
// you want to have some data available in all the templates you need to
// build a complex page
public static function setCommon( $key, $value )
self::$commonVars[ $key ] = $value;
public function set( $key, $value )
$this->vars[ $key ] = $value;
public function execute()
$T = $this->vars;
include( $this->tpl );
$html = ob_get_contents();
return( $html );
A sample template may look like:
Hello, <?= $T[ 'user' ] ?>!
The $T array is the only variable visible to the template (except for $this, which points to the Template instance and the super-variables $_GET, $_POST, etc…), since it’s the only variable defined in the scope where the template has been include()’d
The controller might look like this:
require_once( 'classes/template.php' );
$tpl = new Template( 'templates/helloWorld.php' );
$tpl->set( 'user', 'World' );
print( $tpl->execute() );
I’ve been using a class like that for a couple of years now, without any regret. It’s been used in sites whose content and graphics are now constantly edited by their owners: even though they aren’t programmers, they never had any problem whatsoever in editing or creating their own templates. I truly like it beacuse:
- it’s simple
- it surely isn’t bloated 🙂
- it’s faster than many (most?) of the other templating engines
- it’s as flexible as you need
Of course, the fact that you’re using PHP to create your templates shouldn’t tempt you to start placing business logic inside them!