Simple PHP Template Engine
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) { if($name == 'view_template_file') { throw new Exception("Cannot bind variable named 'view_template_file'"); } $this->vars[$name] = $value; } public function render($view_template_file) { if(array_key_exists('view_template_file', $this->vars)) { throw new Exception("Cannot bind variable called 'view_template_file'"); } extract($this->vars); ob_start(); include($view_template_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
*EDIT* Added checks to make sure that no one tries to binding a variable named view_template_file to prevent somone doing something silly and bind the whole request to the function overriding the variable. Causing a nasty vulnerability
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?
I officially license this code with WTFPL:
http://en.wikipedia.org/wiki/WTFPL
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.
@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.
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!
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 :)
I am not sure I understand the question.
Beautiful article! Could not agree more!
@AntonioCS
@Chad Emrys Minick
I believe what he is referring to is dropping the extract($this->vars);
Without your template acts as part of the view class. In that way all your vars are $this->title and $this->foo but you also have access to functions (@see view helpers like Zend_View_Helper) through the __call magic function inside of your Template class.
All and All nice work.
A similar article was written in 2003 http://www.massassi.com/php/articles/template_engines/ :)
really you still have access to class methods, even with extract(). The example I provided was the simplest template engine to show off how to do it. I really suggest that people do add in view helper support as well. Maybe I’ll write another article sometime showing how to do it.
You woudln’t need the Exception inside __set if you defined a property named ‘view_template_file’
i also love the kiss princip. your words are completely right. template engines are so redundant. Lol they even have great disadvantages. learning a bit php is cool since it can be used on many fields. a kiss tut about using plugins prerendering data would be cool.
Thanks for this simple template class, but I have a question regarding multidimensonial arrays.
How can I achieve to get these filled?
Background:
I have a while loop in which some more variables need to be filled in.
I would appreciate any help on this!
Thanks in advance!
Very good reading, thanks! I agree with everything you said but couldn’t agree more with your clarification on Smarty templating engine. A car on top of another car, and most people just mention the advantages of the car on the top, forgetting the overload you are causing on the bottom car. I would even mention further, the car on the top would need you to learn how to drive in a different way!
I tend to disagree firstly because this breaks the OO, I always try to avoid to usage of magic methods __get and __set. Secondly how would you use this with more complicated structure like a table of results.
@Jonathan
I am curious to why you think that assigning into properties “breaks the OO”. A complicated structure like a table of results doesn’t really add, or take away any complexity in the template. You can still assign the value into the scope of the template, and then loop over it the same way you would in PHP. Even do nested looping!
@Ben
There’s several ways you can do this. You can just assign a multi dimensional array into the template and loop over it like you normally would.
The other way I’ve been thinking about doing a blog about… Using the SPL to make a sort of “lazy iterator” so that the values of the array aren’t filled out until you loop over them. You can simply just assign the object into the view. As you loop over object, it will get the data you need.
extract($this->vars, EXTR_SKIP);
Would prevent overwrite of $view_template_file.
great tip! thanks.