When to use PHP template engines

GG. picture GG. · May 4, 2011 · Viewed 12k times · Source

I am building a website in php with lot of pages and we are a team of 9 working on it. So just want to explore that when should we use PHP template engines and when we shouldn't. So I'm interested in pros and cons of using PHP Template engines so I can make a decision whether to use it in my case or not.

Answer

Bogdan Constantinescu picture Bogdan Constantinescu · May 4, 2011

PHP is a template language.

In my experience so far with various template systems, the conclusion was pretty simple: use none.

Instead, write PHP as it should be written! Never do anything inside a .html besides echo and for/foreach. If you write the code based on a design pattern like MVC this becomes even more obvious: just echo and foreach inside and explain the frontends they should never mess with the code inside <?php and ?>.

It worked for me ever since. It usually was harder for me to explain them Smarty than to explain to never mess with php.

Template systems also add weight to your server (sometimes is just a bit, sometimes you may feel it). It may seem over-optimization at first, but I prefer to keep it as simple as it can be.

Note:

Smarty, for example, is HARDER to spot in a .html file because the only Smarty syntax highlighter I know is a NetBeans plugin and it's pretty beta. PHP, on the other hand, has it syntax highlighted in any decent editor. Also easier for the frontends to spot and not mess with.

Wrap up

Cons (for using template system)

  • Increases server load (lighter or heavier, doesn't matter - you can see it)
  • Induces bad practice (logic wrapped inside template language syntax)
  • No syntax highlighting for template languages' syntax - harder to spot (for coder and frontend)
  • Time spent learning it and teaching it to the frontends
  • Harder to explain to the frontend team (I've taught basic PHP to frontends several times - while many more were already able to write their own 'beginner-level' PHP; I have never taught a frontend Smarty so they can do something other than {$var} )
  • Makes you avoid the REAL problem: logic and presentation separation!
  • Adds extra weight to your project

Pros (for using template system)

  • Extreme boredom (probably the only valid argument)

Template system replacement

  • Logic and presentation separation (I'd suggest MVC for this task and for the pros it provides for other fields of development: easier maintenance, abstract database and so on)
  • Force yourself to write in the view only echo and iteration for echoing: foreach and for should accomplish 99% of the iteration needs; you can also use while and do while