Monthly Archives: January 2011

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.

Using PHP classes to store configuration data

In my last projects I’m using something I think is useful and it’s not a common practice in our PHP projects. That’s is the usage of a plain PHP’s class for the application’s configuration. Let me explain it. Normally we use ini file for configuration. PHP has a built-in function for parse ini file. It converts the ini file into a PHP array

; our conf.ini file
DEF_APP = home
DEF_BCK = main
DEF_FCT = index
AUTH_ADAPTER = Nov\Auth\Def

[PG1]
driver = pgsql
dsn = "pgsql:dbname=pg1;host=localhost"
username = nov
password = nov

And now we use our ini file:

$conf = parse_ini_file("conf.ini", true);
print_r($conf);

Another typical configuration file is xml. We also can use built-in functions within PHP when we want to parse xml files. There are also projects that use plain php files, and even yaml files (especially Symfony users)

There are many standard options. Why I prefer a different one then? I like plain PHP classes because the IDE helps me with autocompletion. The usage is quite simple. Instead of using parse_ini_file function we only need to include our configuration class within our project.

class Conf
{
 const DEF_APP = 'index';
 const DEF_BCK = 'Index\Bck\Main\Page';
 const DEF_FCT = 'init';
 const AUTH_ADAPTER = "Nov\Auth\Def";

 const DB_PG1 = 'PG1';
 const DB_PG1_DRIVER   = 'pgsql';
 const DB_PG1_DSN      = 'pgsql:dbname=pg1;host=localhost';
 const DB_PG1_USERNAME = 'nov';
 const DB_PG1_PASSWORD = 'nov';
}

Sometimes I want to use a variable stored into the application’s configuration but I don’t remember exactly the name of the variable. If I’ve got the configuration stored into a PHP array from a ini file (or xml, yaml, … ). I need to open the configuration file and find the name of the variable to use in my code. With a PHP class IDEs like Netbeans of VIM will pop up an autocompletion hint with the name of the variable

An example of coding autocompletion with Netbeans
The same with VIM

And that’s all. Maybe the worse part of this technique is if our application writes the configuration file (a typical installer.php). In this case we need to build the PHP’s class file and it’s slightly more complicated than writing a simple ini file.

What do you think about it? Do you use another different way?

My VIM configuration for PHP development.

Keeping on with my continuous search for the perfect IDE I’ve resumed my fight against VIM. As someone told me the learning of vim is a road of pain. It’s something like going to the gym. We known that going to the gym is good and healthy but it’s hard and painfully especially at the beginning. The learning curve of vim is hard. Vim is rare, or at least it’s different than all other IDEs. In this post I don’t want to create a vim tutorial (there are a lot of on the web). I want to share my actual vim configuration and the plugins I normally use. The configuration is not very original. It’s based on Matthew Weier O’Phinney configuration. You can find here a great post about vim in Matthew Weier’s blog. VIM is not my default IDE yet. I hope to swap to VIM soon but I feel myself slower when I code comparing with Netbeans or ZendStudio, and slow means less productive but I also feel if invest more time vim can be really productive. Here we are my vim plug-ins:

NerdTree

Great plug-in. Allows to explore filesystem. It’s easy and fast. I use F5 to toogle the NerdTree We move across the filesystem (jk) and open files with “o”. It’s really intuitive. Another great feature of NerdTree are the bookmarks. We select a folder and we type :Bookmark and we easily create a bookmark. Really cool when we work with different projects.

BufferExplorer

We can manage vim’s buffers with standard vim commands(:ls) but I like to use this extension. I’ve mapped BufferExplorer with ç key. I use a spanish keyboard and ç key is a letter I never use and is easily accessible, even for my small hands. When I type ç I can switch between my buffers.

Zen Coding

Really useful when writing HTML
pre#myid>span <Conrol-y>
and we get:

<pre id="myid"></pre>

You can see more examples here

Debugger

We need xdebug plugin installed on our server. I’ve changed the original keys for this plugin because it uses NerdTree ones. I use control + the original keys. For example control + F5 starts the debuger and waits for the debug session from the browser. Xdebug helper for google chrome works fine.

Debuger session

snipMate

Mac developers love Textmate. I’ve never use textmate (I’m a linux user) but this allow us create snippets features in Vim like Textmate’s snippets. It’s a good practice to create the snippets we normally use to increase our productivity. I’ve created several snippets for creating classes, function, for loops, and common pieces of code like that

Command-t

We can open files with :e but commnad-t plugin helps us to open files. I trigger command-t with . Leader is an especial key in vim. We can map this key to a letter. I’ve mapped to “,”

Omni completion

control x – control o. If you have previously created your exuberant tags files, helps you with the autocompletion. Ok it’s not as good a netbeans or eclipse but it works. To create ctags file there is a mkTags bash file under .vim/bin folder

Supertab

snipMate is trigger with tab key but tab key is used to for auto-completion with php plugin (ftp plugin). Supertab plugin magically triggers the plugin we need. I don’t really know how it works but it works (at least as I expect)

Another useful commands

çç: (insert mode) I use çç as esc key because escape key is too far for my small fingers
ç: (normal mode) Buffer explorer
control p: PHPDoc helper
zz: Open all forlds
F7: open close a fold
F6: show/hide line numbers

You can download my vim configuration from google code here

How to configure vim with my setings:

hg clone https://gonzalo123-vim.googlecode.com/hg/ gonzalo123-vim
ln -s gonzalo123-vim/ ~/.vim
ln -s gonzalo123-vim/vimrc ~/.vimrc
ln -s gonzalo123-vim/gvimrc ~/.gvimrc
Follow

Get every new post delivered to your Inbox.

Join 973 other followers