Home > Coding, PHP > Simple PHP Template Engine

Simple PHP Template Engine

September 30th, 2009

PHP for templating?

PHP is a bit of a rare language as it can already template into text in markup with zero modifications or libraries. It is probably one of the big contributing factors why PHP is one of the most popular languages on the web today. (Can’t be the only factor, it didn’t work for ColdFusion) Most other web languages have a one or more templating languages with a different syntax that need to be learned on top of the implementing language. PHP lowers the bar to entry by allowing you to put your PHP code right into your html. But as we all know, sometime in your PHP tour, you will realize the need to separate presentation logic and the application logic. Some developers go running to some other solution that provides a different syntax. I am a bit puzzled on why this seems to be common practice, PHP can provide the same features without throwing another template syntax on top of what PHP already does. You can still achieve the separation needed with a simple class (shown at the end of this article).

I mainly see two solutions that people tend to use over PHP. One solution is to use a premade template engine like Smarty on top of PHP. The other is to use string replacement techniques on a template file.

String replacement… sucks

If you wrote your own template engine most likely using a str_replace or perhaps preg_replace to implement the embedding of dynamic parts of the code. There are two problems with this: One, it’s slow; Secondly it’s difficult to implement all the features needed to provide a robust templating language. Things like formatting functions, control structures etc are a bit clumsy to add to a solution like this. The other option is to implement very simple variable replacement, and then doing your formatting functions, control structures, etc. in your controller and just assign the result to variable replacement, however, that is completely against the point of having a template engine. The separation of presentation logic and app logic gets pretty blurry when you do some of the presentation logic outside of the template.

Did I mention it’s a pretty slow solution?

Smarty and other template engines

Smarty and similar template engines are pretty darn redundant. Here is an example of the workflow for Smarty:

  • Smarty language is parsed
  • Compiled to PHP
  • PHP code is cached
  • PHP code is parsed
  • PHP code is compiled to opcodes
  • If you have a opcode cache, opcodes are cached
  • opcodes are ran

If you don’t see the redundancy there, I’m not doing my job very well. The whole idea of Smarty is like having a car on top of a car and believing it improves your gas mileage. Most people complain that the Smarty syntax is better than PHP’s for templating. Bull. There is nothing really gained in Smarty’s syntax, it only looks more concise, but in reality there is not enough gains to support having the bloat on top of PHP. You save a couple of keystrokes, big deal. {$var} vs. < ?=$var?>. That is micro-optimization if I ever saw it. PHP control structres and formatting are much more concise and cleaner looking than Smarty’s. Smarty doesn’t work with most IDE’s, so with PHP you gain everything you get with your IDE (or editor), code completion, highlighting, syntax linting, and more!

common (lame) excuses

My designers don’t know PHP

They also don’t know the templating language you pick for them. If they are going to learn something, have them just learn enough PHP to do their templating. The syntax of something like smarty isn’t really easier to learn at all.

I can’t use PHP! that’s not separating the presentation logic!

Actually you can achieve clear separation. See the class code below.

PHP syntax sucks for Templating

No, it’s just fine. Really.

I don’t trust my designers with PHP

You are using a templating engine to solve the wrong problem. Template engines are meant to achieve higher maintainability through separation of logic. What you are trying to solve is a flaw in your job culture. These days, designers don’t need to write bad server side code to cause a lot of hurt, they can write some horrid client side code that can be just as bad. Also your templating engine should be flexible in case you run into a wall in implementation. You don’t want to paint yourself in a architectural corner because you don’t do code review. (if you really don’t trust your designers, only let them make static html mockups, have a jr. developer make them into templates.)

I don’t like PHP

Me either, that’s why I work with Java and JSP.

The Code:

< ?php
class Template {
  private $vars  = array();
 
  public function __get($name) {
    return $this->vars[$name];
  }
 
  public function __set($name, $value) {
    $this->vars[$name] = $value;
  }
 
  public function render($file) {
    extract($this->vars);
    ob_start();
    include($file);
    return ob_get_clean();
  }
}

Usage:

main.php template:

<html>
<head>
  <title>< ?php echo $title; ?></title>
</head>
<body>
<h1>< ?php echo $title; ?></h1>
<div>
< ?php echo $content; ?>
</div>
</body>
</html>

content.php:

<ul>
< ?php foreach($links as $link): ?>
<li>< ?php echo $link; ?></li>
< ?php endforeach; ?>
</ul>
<div>
< ?php echo $body; ?>
</div>

controller.php:

$view = new Template();
 
$view->title = "hello, world";
$view->links = array("one", "two", "three");
$view->body = "Hi, sup";
 
$view->content = $view->render('content.php');
echo $view->render('main.php');

Other PHP templating solutions you may want to check out

PHP Savant
Zend View, Part of the Zend Framework

Chad Emrys Minick Coding, PHP

  1. October 27th, 2009 at 17:40 | #1

    This example gave me the necessary foundation to understand the concept behind template engines. It’s very simple and easy to approach. I plan on using something similar to it in my backend’s next version. Are there any stipulations on using this code?

  2. Chad Emrys Minick
    October 27th, 2009 at 17:42 | #2

    I officially license this code with WTFPL:
    http://en.wikipedia.org/wiki/WTFPL

  3. Frank Munch
    December 12th, 2009 at 01:49 | #3

    You don’t mention the most important problem with Smarty – that some syntax is very clumsy, it is not object-oriented, and parametrization is difficult.
    But the value of it is that it is easier to learn than PHP, and definitely less dangerous.

  4. Chad Emrys Minick
    December 13th, 2009 at 12:47 | #4

    @Frank Munch
    I don’t think it’s easier to learn than PHP at all. There is no evidence towards that. And I think I covered the less dangerous part in the article.

  5. February 1st, 2010 at 09:41 | #5

    There is a small problem with your Template class when using arrays.

    Try this:

    [code]
    $view->a = array('foo');
    var_dump($view->a); //foo is there, all fine

    $view->a[] = 'bar';
    var_dump($view->a); //bar is not there!
    [/code]

    To solve this, you need to return the __get by reference, like this:

    [code]
    public function &__get($name){
    if (isset($this->vars[$name])) return $this->vars[$name];
    else return null;
    }
    [/code]

    It’s also advisable to overload isset and unset

    [code]
    public function __isset($name) {
    return isset($this->vars[$name]);
    }

    public function __unset($name) {
    unset($this->vars[$name]);
    }
    [/code]

    Cheers!

  6. March 3rd, 2010 at 11:56 | #6

    Why not just use title ?> since you are including in the class code and you already have the __set method so it should be simple to change to using $this in the template :)

  7. Chad Emrys Minick
    March 11th, 2010 at 12:23 | #7

    I am not sure I understand the question.

  1. June 15th, 2010 at 00:07 | #1