Translation: Template Engineers in PHP - Summary

Original author: Fabien Potencier
  • Transfer
Translation of Fabien Potencier blog post discussions on PHP templating and Twig.

-----------------------------------------------------------------------
My post on template engines in PHP (comment translation ) has received more than 70 comments at the moment. It can be noted that many of them are well thought out and reasoned. Thanks to everyone who spent their time participating in a constructive discussion. I am really proud that the PHP community (at least the part of it that reads my blog) is able to discuss this risky topic without embarking on a flame war! I am also impressed with the number of people who want to promote their own template engines;)

Before starting to answer some questions, I would like to remind you that I like templates in pure PHP. And you need to remember that symfony uses templates in pure PHP from the very beginning. As a fact, I defended the use of pure PHP for templates from my first PHP project and never used a third-party template engine. So, I am not against PHP for templates; I just realized that the limitations of PHP, as a template engine, began to annoy me more and more.

As Eli pointed out , “I [Fabien] present PHP templates in this form because I want to promote the template engine that I created”

I also liked the comment from Tchalvak: “The question of which PHP is better or the template engine is not the most important one, it is much more important (and which is easier to answer) is to use templates or not. Templates - and presentation highlighting - are needed. And in what form it is presented, is not so important. ”He summed up the discussion well.

I understand all the points raised in the comments, and, in a simple way, I agree with most of them. Now I want to answer some interesting comments.

Twig. Cause.


I started looking for a template engine a few months ago. People who know me know that I do not like to reinvent the wheel. Therefore, I did not want to create my new library from scratch.

I searched for good templating engines, tried some of them, and eventually found Twig. And as soon as I started using it, I realized that this is the diamond that I was looking for (for its functionality and simple, beautiful architecture). And, since Twig was not an independent project, I began to rewrite it. After some improvements, such as the sandbox mode, I decided to contact Armin and talk about the future of Twig.

Those. you're not for sale ... still?


Even if you do not believe in my arguments, this is normal. I do not want to make a universal template engine out of Twig for PHP. I really think that Twig is not the only one on the template market, but I am the first to decide that it will not be used in all new PHP projects!

If you are looking for a templating engine for PHP cheat and having the built-in ability to inherit templates, blocks, auxiliary functions (helpers) and more, the good news is that a few weeks ago I introduced the Symfony template component . This is a completely standalone component that does not depend on anything, and I'm sure that many who want to use PHP in their templates will love this project.

And even better - you can use Twig and the Symfony Templating component to get the best results. Use the component for all your templates, and Twig if you need the sandbox mode.

About the syntax


Lots of syntax comments and PHP syntax issues that I raised. This is not the beauty of the syntax, and if you think that my arguments are a discussion of the "color of bicycle sheds" (approx. Russian version ), think again.

The key point of my argument is that the template engine should strive for a middle ground (?? sweet spot). Pattern designers must find a compromise in the availability of opportunities - enough, but not too much. As I said in a previous post, the template language refers to presentation logic . And, of course, simple conditions and cycles are part of the presentation logic. But do you want to use the functionarray_chunk()in templates? Probably not. This should be implemented in the controller or model, depending on what you want to do.

The templates also have a lot of HTML code with a little PHP content. And this piece of code is completely unacceptable to me:
<? php
    if ($ items) {
        foreach ($ items as $ item) {
            echo "* {$ item} \ n";
        }
    } else {
        echo "No item has been found. \ n";
    }
?>


Many seem to like short PHP tags. The first is math. If you compare the record <?= $var ?>with the record <?php echo $var ?>, you will see a difference of 7 characters, not 2. But this is not the main problem.

In addition to problems with XML support and the fact that the configuration parameter short_open_tagdiffers between hosting providers, this is also a matter of standardizing code:
  • PEAR : “Always use a <?php ?>short version to separate PHP code <? ?>. This is mandatory under the PEAR agreement and is also the most flexible way to use PHP code on different operating systems and different configurations. "
    " Always use <?php ?>to delimit PHP code, not the <? ?>shorthand. This is required for PEAR compliance and is also the most portable way to include PHP code on differing operating systems and setups. ”
  • Zend : “
    Short tags are never allowed.” “Short tags are never allowed.”


Pear and Zend are quite serious projects, so they had reasons to prohibit short tags, right?

But as Eli mentioned in his post, I would also be glad to know that PHP addressed this problem: "... there are a number of people (including me [Eli]) who are thinking of proposing a new directive feature short_tagsin PHP, which makes it possible not only to include and turn it off. But also adding the 3rd option - which will allow <?= ?>, prohibiting <? ?>"

About layout designers


(approx. the original web-designers will be translated hereinafter as a layout designer). The

debate is not about whether layout designers should understand PHP or not. And, of course, not that layout designers are not smart enough. Of course, they can learn a little PHP ... until they learn too much and start writing code that is not related to their templates (for example, select records directly from the database). Well, of course, they would not have made such a mistake if they had known about the MVC pattern. But stop, they are no longer coders - they are programmers.

Finding a balance is to provide a tool that helps layout designers not to step on the rake. And, I think that everyone will agree with me that PHP did their job poorly in setting these restrictions.

Shielding


Some comments advocate that shielding should be done in controllers. This will not work. As John Campbell wrote: “The problem is that the controllers do not know what will be output, and they also don’t know exactly how to screen”

The problem itself is not simple. On the one hand, programmers must deal with shielding, but cannot do this in controllers. On the other hand, coders should not care about coders, but only in templates can it be done with enough information. Therefore, automatic shielding is the best compromise for me, plus the fact that the default application is “practically” safe is also an advantage.

Speaking of automatic shielding, we can say that I know enough about this, because in symfony this feature has existed since 2006. I can tell you that the overhead of the speed of such functionality is very large. In Twig, this all compiles, and therefore there is no overhead.

About the Sandbox


The sandbox mode is not oriented to layout designers. Basically, this applies to situations when people “outside” can change the templates (think of webmasters who customize the templates of their CMS or blog platform from the management system).

The development of Dwoo and Smarty security is the right step in this direction, but not as powerful as the full sandbox mode. As far as I understand, all this is mainly about allowing PHP code in templates or not, as well as limiting the available PHP functions (correct me if I'm wrong).

Sandbox mode controls everything from valid tags to allowed object methods ( Twig documentation explains the concept and how it works)

About speed


Most template engines compile templates into PHP code. Therefore, the speed of lexing, parsing, and compilation does not play a big role, which is the speed of execution. Below is a compiled version of the template Hello {{ name }}:
/ * Hello {{name}} * /
class __TwigTemplate_1121b6f109fe93ebe8c6e22e3712bceb extends Twig_Template
{
  public function display ($ context)
  {
    $ this-> env-> initRuntime ();
 
    // line 1
    echo "Hello";
    echo (isset ($ context ['name'])? $ context ['name']: null);
  }
}


Many are worried about debugging. As you can see, the generated code is very clean, contains the name and lines of the original template. This should be more than enough to easily debug all problems.


You can find this incredibly verbose than the PHP version, and of course the PHP version will be incredibly simpler:
Hello <? Php echo $ name?>


But pay attention to the generated code of most template engines and you will see for yourself that Twig generates the cleanest and shortest version.

At the request of many, I rewrote the tests, combining the compilation and rendering phases. As I expected, this did not change the numbers much. Compiling such simple templates is not important by the time they are rendered 10,000 times.

I also tested templates in pure PHP. Below is an updated table:

LibraryTime (sec)Memory (Kb)
Pure php2.4114
Twig3383
Phptal3.8598
Dwoo6.91 645
Smarty 212.9610 *
Smarty 314.9799 *
Calalypso34.3614
eZ Templates532 783

Please note that the amount of memory used by Smarty is much less than in my previous test, because I wrapped the whole cycle in ob_start()/ob_end_clean()which it was unfair to other template engines. This has now been fixed.


As expected, PHP is faster than Twig for simple templates. But the more complex they are, the smaller the difference will be, thanks to the cleanliness of the code that Twig generates.

Test scripts were run from the command line without PHP accelerators, which in this case would still not help, because the whole test takes place in one PHP process.


Tests you can download here: fabien.potencier.org/benchmarks.tgz

Twig and Symfony


This section is for those who are interested in implementing Twig in Symfony.

Symfony 1.3 / 1.4


Obviously, Twig will not be part of symfony 1.3 since at the end of next week the deadline for the development of functionality (feature-freeze deadline) is suitable, and also because symfony 1.3 is an evolution of symfony 1.2, not a revolution.

If someone wants to make Twig a symfony 1.3 plugin, start a discussion on the symfony developer mailing list and I will help you get started.


Symfony 2.0


At the moment, nothing concrete has been decided regarding Symfony 2, but Twig will not be the default template engine. I think Twig will be available as an optional plugin that integrates well with the kernel. For example, it can be used to generate a backend (admin-generator) - to simplify its configuration (customization).

And, thanks to the Symfony Templating component , developers can use Twig and pure PHP together, depending on the needs.

So, if you do not want to mess with template engines - use pure PHP; but if you want to win using Twig you can use it (it will be built-in). And of course, if you have other plugins they will not become a problem.

Total


I hope that this post answered some questions raised in the comments.

Also popular now: