Category Archives: haanga

PHP Template Engine Comparison. Part 2 (versus Plain PHP)

In my last post I created a small (and very personal) test of different templating engines in PHP (Smarty, Haanga and Twiw). Someone posted a comment asking for the comparison between those template engines and old school phtml. OK I’ve done some tests. It’s a bit difficult to create the template inheritance (without cloning one of the template engines and creating a new one) so I have one approximation with a simple include. It’s not the same but it’s similar. I’ve also implemented cycle filter (OK I’ve borrowed getCycle function from Twig. Not really implemented ;) )

Using plain PHP files as template is a big temptation. They’re easy to implement and fast. But you need to take care of security issues. For example if you work together with designers, using a template engine is a good solution. It sandboxes our templates and separates the business logic from the HTML. With plain PHP files is very easy to put business logic within templates.

Here we are my examples:

<?php  /* PHP plain. indexFull.phtml */?>
<html>
    <head>
        <title><?= $title ?></title>
    </head>
    <body>
        <h2>An example with <?= ucwords(strtolower($title)) ?></h2>
        <b>Table with <?= $number ?> rows</b>
        <table>
            <?php foreach ($table as $row) { ?>
            <tr bgcolor="<?= cycle(array('#aaaaaa', '#ffffff'), $row['id']) ?>">
                <td><?= $row['id'] ?></td>
                <td><?= $row['name'] ?></td>
            </tr>
            <?php } ?>
        </table>
    </body>
</html>

and the PHP:

$time = microtime(TRUE);
$mem = memory_get_usage();

define('BASE_DIR', dirname(__file__));

class DirtyTemplateEngine
{
    protected $_templateDir = null;
    public function __construct($path)
    {
        $this->_templateDir = $path;
    }

    function display($template,array $vars) {
        extract($vars);
        ob_start();

        function cycle($values, $i)
        {
            if (!is_array($values) && !$values instanceof ArrayAccess) {
                return $values;
            }

            return $values[$i % count($values)];
        }
        include($this->_templateDir . '/' . $template);
        echo ob_get_clean();
    }
}

$tpl = new DirtyTemplateEngine(BASE_DIR . "/php/templates");

$rows = 50;
$data = array();
for ($i = 0; $i < $rows; $i++) {
    $data[] = array('id' => $i, 'name' => "name {$i}");
}

$tpl->display('indexFull.phtml', array(
    'number' => $rows,
    'title'  => 'php',
    'table'  => $data
));

print_r(array('memory' => (memory_get_usage() - $mem) / (1024 * 1024), 'seconds' => microtime(TRUE) - $time));

And with template “inheritance”
I know that maybe this test is not comparable with “real” template inheritance

<?php  /* PHP plain. index.phtml */?>
<html>
    <head>
        <title><?= $title ?></title>
    </head>
    <body>
        <h2>An example with <?= ucwords(strtolower($title)) ?></h2>
        <b>Table with <?= $number ?> rows</b>
        <?php include 'block.phtml' ?>;
    </body>
</html>
<?php  /* PHP plain. block.phtml */?>
<table>
    <?php foreach ($table as $row) { ?>
    <tr bgcolor="<?= cycle(array('#aaaaaa', '#ffffff'), $row['id']) ?>">
        <td><?= $row['id'] ?></td>
        <td><?= $row['name'] ?></td>
    </tr>
    <?php } ?>
</table>
(50 rows) Smarty Twig Haanga PHP
Simple template Memory: 0.684497
Time: 0.023710
Memory: 0.598434
Time: 0.025444
Memory: 0.124019
Time: 0.004004
Mem: 0.026512
Time: 0.001536
Template Inheritance Memory: 0.685134
Time: 0.023761
Memory: 0.619461
Time: 0.028100
Memory: 0.133472
Time: 0.005005
Mem: 0.026512
Time: 0.001536
(1000 rows) Smarty Twig Haanga PHP
Simple template Memory: 1.222743
Time: 0.094762
Memory: 1.033226
Time: 0.196187
Memory: 0.558811
Time: 0.043151
Mem: 0.576526
Time: 0.028120
Template Inheritance Memory: 1.194095
Time: 0.090528
Memory: 1.054237
Time: 0.191694
Memory: 0.646381
Time: 0.044402
Mem: 0.537937
Time: 0.043996

Haanga really rocks again. The performance is very similar than plain PHP templating. Plain PHP is obviously the fastest but Haanga is almost the same. It’s a pity the lack of complete documentation (it’s very hard look into the source code to find features and examples). As Cesar Rodas (Haanga’s developer) told us in a comment Haanga generates self-contained PHP code. Because of that the performance is close to plain PHP execution.

Another useful links about it here and here.

PHP Template Engine Comparison

I’m going to face a project using a template engine with PHP. Because of that I’m will perform a small benchmark test of several PHP template engines. That’s not an exhaustive performance test. It’s only my personal test. Template engines has a lot of features but I normally only use a few of them and the other features very seldom. In this performance test I will check the same features under different template engines to see the syntax differences and the performance. The template engines selected for the test are Smarty, Twig and Haanga. Let’s start:

Smarty. v3.0.6
It’s probably the most famous template engine. It’s a mature project. For years it was “the” template engine and the others were the “alternatives”. It was famous because of the speed.

Twig. v1.0.0-RC1-8
It’s a new template engine developed by Fabien Potencier, the creator of the symfony framework. One of the PHP’s rock stars nowadays. It’s going to be an important part of the new symfony 2.0 framework. Twig borrows the template syntax from Django (probably the main web framework if we work with Python)

Haanga. v1.0.4-14
It’s another new template engine using the Django style. It was developed for Menéame by César Rodas.

I’ve decided to create two tests. One with a simple template and another using template Inheritance. The both cases renders one html page using one variable, filters and for loop to create an HTML table. Basically I’ve created those test because they’re the things I normally use. I will run the test with an HTML table of 50 rows and 1000 rows

Simple template

Smarty

{* Smarty. indexFull.tpl*}
<html>
    <head>
        <title>{$title}</title>
    </head>
    <body>
        <h2>An example with {$title|capitalize}</h2>
        <b>Table with {$number|escape} rows</b>
        <table>
{foreach $table as $row}
            <tr bgcolor="{cycle values="#aaaaaa,#ffffff"}">
                <td>{$row.id}</td>
                <td>{$row.name}</td>
            </tr>
{foreachelse}
            <tr><td>No items were found</td></tr>
{/foreach}
        </table>
    </body>
</html>

And the PHP conde:

// index.php
$time = microtime(TRUE);
$mem = memory_get_usage();

define('BASE_DIR', dirname(__file__));
require(BASE_DIR . '/include/smarty/Smarty.class.php');

$smarty = new Smarty();

$smarty->setTemplateDir(BASE_DIR . '/smarty/templates');
$smarty->setCompileDir(BASE_DIR . '/smarty/templates_c');
$smarty->setCacheDir(BASE_DIR . '/smarty/cache');
$smarty->setConfigDir(BASE_DIR .'/smarty/configs');

$smarty->assign('title', "smarty");

$rows = 1000;
$data = array();
for ($i=0; $i<$rows; $i++ ) {
    $data[] = array('id' => $i, 'name' => "name {$i}");
}
$smarty->assign('table', $data);
$smarty->assign('number', $rows);
$smarty->display('indexFull.tpl');

print_r(array('memory' => (memory_get_usage() - $mem) / (1024 * 1024), 'seconds' => microtime(TRUE) - $time));

Twig

{#  Twig. indexFull.html #} 
<html>
    <head>
        <title>{{ title }}</title>
    </head>
    <body>
        <h2>An example with {{ title|title }}</h2>
        <b>Table with {{ number|escape}} rows</b>
        <table>
            {% for row in table %}
            <tr bgcolor="{{ cycle(['#aaaaaa', '#ffffff'], row.id) }}">
                <td>{{ row.id }}</td>
                <td>{{ row.name }}</td>
            </tr>
            {% endfor %}
        </table>
    </body>
</html>

And the PHP code:

// index.php
$time = microtime(TRUE);
$mem = memory_get_usage();

define('BASE_DIR', dirname(__file__));
require_once BASE_DIR . '/include/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem(BASE_DIR . '/twig/templates');
$twig = new Twig_Environment($loader, array(
            'cache' => BASE_DIR . '/twig/compiled',
            'auto_reload' => true
        ));
$template = $twig->loadTemplate('indexFull.html');

$rows = 1000;
$data = array();
for ($i = 0; $i < $rows; $i++) {
    $data[] = array('id' => $i, 'name' => "name {$i}");
}

$template->display(array(
    'number' => $rows,
    'title'  => 'twig',
    'table'  => $data
));

print_r(array('memory' => (memory_get_usage() - $mem) / (1024 * 1024), 'seconds' => microtime(TRUE) - $time));

Haanga

{#  Haanga. indexFull.html #} 
<html>
    <head>
        <title>{{ title }}</title>
    </head>
    <body>
        <h2>An example with {{ title|title }}</h2>
        <b>Table with {{ number|escape}} rows</b>
        <table>
            {% for row in table %}
            <tr bgcolor="{% cycle '#aaaaaa' '#ffffff' %}">
                <td>{{ row.id }}</td>
                <td>{{ row.name }}</td>
            </tr>
            {% endfor %}
        </table>
    </body>
</html>

And the PHP code:

// index.php
$time = microtime(TRUE);
$mem = memory_get_usage();

define('BASE_DIR', dirname(__file__));
require(BASE_DIR . '/include/Haanga.php');

Haanga::configure(array(
    'template_dir' => BASE_DIR . '/haanga/templates',
    'cache_dir' => BASE_DIR . '/haanga/compiled',
));

$rows = 1000;
$data = array();
for ($i=0; $i<$rows; $i++ ) {
    $data[] = array('id' => $i, 'name' => "name {$i}");
}
Haanga::Load('indexFull.html', array(
    'number' => $rows,
    'title'  => 'haanga',
    'table'  => $data
    ));

print_r(array('memory' => (memory_get_usage() - $mem) / (1024 * 1024), 'seconds' => microtime(TRUE) - $time));

With template Inheritance

With this test I use the same php file, changing template name from indexFull to index.

Smarty

{* Smarty. index.tpl*}
{extends file="layout.tpl"}
{block name=table}
<table>
{foreach $table as $row}
    <tr bgcolor="{cycle values="#aaaaaa,#ffffff"}">
        <td>{$row.id}</td>
        <td>{$row.name}</td>
    </tr>
{foreachelse}
    <tr><td>No items were found</td></tr>
{/foreach}
</table>
{/block}
{* Smarty. layout.tpl*}
<html>
    <head>
        <title>{$title}</title>
    </head>
    <body>
        <h2>An example with {$title|capitalize}</h2>
        <b>Table with {$number|escape} rows</b>
        {block name=table}{/block}
    </body>
</html>

Twig

{#  Twig. index.html #} 
{% extends "layout.html" %}
{% block table %}
<table>
    {% for row in table %}
    <tr bgcolor="{{ cycle(['#aaaaaa', '#ffffff'], row.id) }}">
        <td>{{ row.id }}</td>
        <td>{{ row.name }}</td>
    </tr>
    {% else %}
    <tr><td>No items were found</td></tr>
    {% endfor %}
</table>
{% endblock %}
{#  Twig. layout.html #} 
<html>
    <head>
        <title>{{ title }}</title>
    </head>
    <body>
        <h2>An example with {{ title|title }}</h2>
        <b>Table with {{ number|escape}} rows</b>
        {% block table %}{% endblock %}
    </body>
</html>

Haanga

{% extends "layout.html" %}
{#  Haanga. index.html #} 
{% block table %}
<table>
    {% for row in table %}
    <tr bgcolor="{% cycle '#aaaaaa' '#ffffff' %}">
        <td>{{ row.id }}</td>
        <td>{{ row.name }}</td>
    </tr>
    {% endfor %}
</table>
{% endblock %}
{#  Haanga. layout.html #} 
<html>
    <head>
        <title>{{ title }}</title>
    </head>
    <body>
        <h2>An example with {{ title|title }}</h2>
        <b>Table with {{ number|escape}} rows</b>
        {% block table %}{% endblock %}
    </body>
</html>

Outcomes of the tests:

(50 rows) Smarty Twig Haanga
Simple template Memory: 0.684497
Time: 0.023710
Memory: 0.598434
Time: 0.025444
Memory: 0.124019
Time:  0.004004
Template Inheritance Memory: 0.685134
Time: 0.023761
Memory: 0.619461
Time: 0.028100
Memory: 0.133472
Time: 0.005005
(1000 rows) Smarty Twig Haanga
Simple template Memory: 1.222743
Time: 0.094762
Memory: 1.033226
Time: 0.196187
Memory: 0.558811
Time: 0.043151
Template Inheritance Memory: 1.194095
Time: 0.090528
Memory: 1.054237
Time: 0.191694
Memory: 0.646381
Time: 0.044402

Haanga really rocks in the test. It’s the fastest in all cases and it’s the best using memory. The main problem I’ve seen with Haanga is the lack of documentation. When I wanted to use the cycle filter (to create the zebra style in the HTML table) I didn’t find anything about it. I had to browse the source code and finally I found it in one tests. Whereas Smarty documentation is brilliant and Twig is good enough.

The HTML template syntax is almost the same with Twig and Haanga (in fact both of them are Django style). Smarty is a bit different but is very similar. The PHP part in Smarty looks like a bit old fashioned compared with Haanga and Twig, but it’s really easy to use.

The performance of Twig and Smarty are similar. Twig is slightly better. But with simple templates i’ts almost the same.

Follow

Get every new post delivered to your Inbox.

Join 869 other followers