“Why using templates engines if PHP is itself a template engine?” said
Karlus some time ago.
The answer is: The templates engines can be a great help when you're using a PHP framework that is built on modules(using MVC design pattern) where is necessary to fetch pieces of HTML to build a page, separating all code of PHP from HTML.
But the overhead of this templates engines is enormous, because of the all parsing envolved. So templates engines is not all about a sea of roses.
I have used
Smarty for this kind of work for a long time and, in my opinion, is the best.
When i read this
article i realized
Karlus point of view. So based on this idea i have developed a small class that enables all funcionality that
Smarty has (witch i use) but using the PHP natively as the parser.
It's a class with only 160 lines of code(without comments), so don't expect too much...
Features:
Using templates that are PHP files
Including templates inside templates
Caching with expired system in seconds or without expiration
Caching with id's
Plugin system, as simple as you can get
Discover the diferences with a simple template:
Smarty template (index.tpl) |
<html>
<body>
{include file="header.tpl"}
Title: {$title}
List:
{foreach from=$list item=list_item}
{$list_item}
{/foreach}
</body>
</htm>
|
Smarty object creation (index.php) |
require_once('lib/smarty/Smarty.class.php');
$smarty =& new Smarty();
$smarty->template_dir = 'smarty/templates/';
$smarty->compile_dir = 'smarty/templates_c/';
$smarty->cache_dir = 'smarty/cache/';
$smarty->caching = 1;
$smarty->assign('title', 'My Title');
$smarty->assign('intro', 'The intro paragraph.');
$smarty->assign('list', array('cat', 'dog', 'mouse'));
$smarty->fetch('index.tpl');
|
|
My Template (index.tpl) |
<html>
<body>
<?=$this->includeTemplate("header.tpl");?>
Title: <?=$title;?> <br />
List: <br />
<?php foreach ($list as $item):?>
<?=$item;?> <br />
<?php endforeach; ?>
<html>
<body>
|
My Template object creation (index.php) |
require_once('lib/Template.php');
$tpl =& new Template();
$tpl->setTemplatesPath('templates/');
$tpl->setCache(true);
$tpl->setCachePath('cache/');
$tpl->setCacheId('nuno');
$tpl->setExpire(0);
$tpl->assign('title', 'My Title');
$tpl->assign('intro', 'The intro paragraph.');
$tpl->assign('list', array('cat', 'dog', 'mouse'));
$tpl->fetch('index.tpl');
|
Results
The time results shown below, were measured with average results to have a more accurate benchmark.
The benchmarking was made in a Celeron 2400Mhz with 512Mb of RAM.
The Y axis corresponds to the average time in seconds per request and the X axis to the number of requests.
Download
You can download the source code
here.