#1
  1. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046

    Do template engines make sense in PHP?


    Hi,

    since this discussion keeps popping up, I thought I'd make a thread about it. Here's an argument by Northie against template engines:

    Originally Posted by Northie
    PHP is a templating engine, so I see no problems with having spaghetti code in the view, in this context anyway.

    smarty is just spaghetti code with smarty flavoured source rather than php flavoured source. It adds untold layers of complexity, extra processing and is far less portable (I've ni)
    First of all, I disagree with PHP being a template engine itself. It's an all-purpose language that simply happens to be embeddable into HTML (like many other languages). I mean, I could embed C into HTML if I wanted. Would that make C an HTML template engine?

    A template engine for me is a specialized language that does nothing but generate templates. It's supposed to have basic control structures (foreach, if, etc.) and special features like template inheritance and nothing else.

    If you (mis)use PHP as a template engine, the separation of program logic and presentation is purely conventional. You can use any PHP function you want -- and we all know that people will do that, especially when they're in a hurry. So you're likely to end up with HTML tags flying around in PHP logic like in "good old times".

    With PHP, you cannot even pass template values cleanly. You have to define local variables (which may interfere with existing ones), include the script and hope it doesn't do anything but echo HTML.

    So I'd always use external template engines, even for simple scripts. Execution speed also isn't an argument, because Smarty, Twig etc. all have a caching feature that will save the templates as HTML/PHP templates.

    But I agree that current PHP template engines aren't perfect. They indeed produce spaghetti code, because the language tags are simply injected into the HTML. There should be a kind of "unified" language that uses HTML elements as native objects. If you want to know what's possible with template engines, have a look at Haml for Ruby.
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,007
    Rep Power
    9398
    Most of the reasoning I know behind "template engines" in PHP is so that a web designer doesn't have to know PHP. Biggest argument in favor of it that I know: you can limit what the writer can do.

    I'm a PHP developer, so if you gave me templates written in PHP then I would use it as PHP. Call whatever functions I want, peek at whatever variables I want, basically do whatever I want to in order to accomplish my goal. A template language forces me to work within some constraints and the language itself may be designed to work best within them; if I start doing weird stuff then maybe I'll uncover things I shouldn't.

    As for PHP, it's not a templating language but it certainly can be used as one. If I were writing templates for other developers to work on, I would make them in PHP because I know that the developers are familiar with the language and practices.
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Sep 2002
    Location
    Seattle, U.S.A.
    Posts
    712
    Rep Power
    12
    From what I read PHP was originally supposed to be a templating language, but obviously it's grown since then.

    I think there's a place for template libraries like Smarty, and they do help enforce a separation code and presentation which is great. If your organization needs to have separation enforced through a library then great. Though you can abuse smarty too and allow php in your templates and your back where started from.

    Why can't you pass values cleaning via PHP? All the PHP mvc frameworks out there have figured out how to do it.

    For example, this is bastardized a bit from the CI framework:

    PHP Code:

    $data 
    = array();
    $data['places'] = $placeModel->getPlaces();
    $data['people'] = $peopleModel->getPeople();

    $html loadView'admin/dashboard'$data );

    function 
    loadView($viewName$data null) {
        if (!
    defined('VIEW_PATH')) {
            
    define('VIEW_PATH'dirname(__FILE__) . '/views/');
        }
        
    $fileName $viewName '.php';

        if (
    is_array($data) && count($data) > 0) {
            foreach (
    $data as $key => $var) {
                $
    $key $var;
            }
        }

        if (
    is_file(VIEW_PATH $fileName)) {
            
    ob_start();
            include 
    VIEW_PATH $fileName;
            
    $html ob_get_contents();
            
    ob_end_clean();
        } else {
            exit(
    'Unknown view' VIEW_PATH $fileName);
        }

        return 
    $html;

  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Posts
    73
    Rep Power
    36
    Check out Savant. I used it as a base for my own templating engine when I had PHP projects. Removes that local variable issue by creating a template object while still retaining PHP syntax and functionality in the templates.
  8. #5
  9. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,007
    Rep Power
    9398
    Re:variables I have functions like
    PHP Code:
    function include_clean(/* $file, array $args = array() */) {
        if (
    func_num_args() >= && is_array(func_get_arg(1)) {
            
    extract(func_get_arg(1));
        }
        include 
    func_get_arg(0);

  10. #6
  11. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,317
    Rep Power
    7170
    For the duration of this post when I say 'template engine', I mean a template engine written in PHP that parses templates that are not written in PHP. It is of course completely possible to have a template engine written in PHP that adds features like inheritance and scope limitations to templates that are also written in PHP, but I classify those as normal PHP.

    PHP itself is not a template engine, but one could argue that it was originally designed primarily as one. Features like short tags and the alternative block syntax support this notion. Nonetheless, the ability to intersperse HTML and PHP make it very effective as a template engine, and a subset of PHP functionality could definitely be classified as a template engine.

    There are valid reasons to use a template engine, but for most scripts I see them as unnecessary. There are two common arguments that I see raised in support of template engines that I completely disagree with:


    The first is this:
    PHP as a template engine, the separation of program logic and presentation is purely conventional
    I am 100% OK with this. In my mind, writing good code is purely conventional, period. Separation of business logic and presentation logic is a critical and fundamental programming concept; if a programmer is incapable of properly separating programming concerns they are not going to get anywhere near my code base. Yes, a template engine will help them properly separate program logic and presentation logic, but if they can't figure that out on their own it is virtually a guarantee that they will screw up something else somewhere in the code. For these reasons, I view a dedicated template engine as complete unnecessary for purposes of proper code separation.


    The second is this:
    Most of the reasoning I know behind "template engines" in PHP is so that a web designer doesn't have to know PHP.
    This argument has never made any sense to me.

    Does the web designer know nothing about code? Then they wouldn't be able to program an HTML template anyway.

    Do they know HTML but don't understand the basic concepts of programming (control loops and variables)? Any template engine that provides control structures is going to utilize exactly the same basic concepts; if they can understand the template engine, they can understand PHP.

    Do they understand basic concepts of programming but can't remember PHP syntax? They're definitely not going to have an easier time remembering the syntax of a template engine either. Is it that much easier to remember:
    Code:
    {foreach from=$x item=$y key=$z}{/foreach}
    vs
    PHP Code:
    foreach($x as $z => $y): endforeach; 
    (Yes, the Smarty version has named parameters, but all that means is you have to remember the names instead of the order)

    Do they understand both the basic concepts of programming and have a good grasp of syntax? Then why not just have them write PHP.

    Afraid they'll try to run database queries from inside the template? If your designer is trying to run database queries you need to rethink their job title, and if they're trying to do it from within a template you need to rethink their employment.


    However, one argument in favor of template engines that I do agree with is this:
    Biggest argument in favor of it that I know: you can limit what the writer can do.
    I agree, this is the biggest argument in favor of template engines. There are definitely situations where you need to be able to restrict what a template writer can do - for example, when your template writers are users who are editing the templates via an online form.


    Another major argument in favor of templates is when you need to share the template across multiple programming languages - like PHP and JavaScript. Due to the complexity of PHP and JavaScript, it is not really possible to share a template written in one with the other (short of invoking the other to parse it). However, equivalent template engines can obviously be written in both, allowing the templates to be shared.
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around

IMN logo majestic logo threadwatch logo seochat tools logo