Preferred way to combine PHP and HTML?

13,524

Solution 1

If you want to separate the PHP from the HTML you can use a template engine (Like smarty http://www.smarty.net/).

Solution 2

Personally, I see no reason to add a template system/language into the mix, when PHP is already a prefectly good solution.

My preferred approach is to separate the display from the logic of the application. This could take the form of a full blown MVC framework. However, it could also be a simple matter of how you go about writing your code.

Expansion:

Ever since making the mistake of interspersing my HTML with copious amounts of ASP code, I have tried to separate page logic from display. Within a single page, this means placing all of the page logic at the top, storing the information to be displayed in variables and then echoing them out within the HTML at the bottom of the PHP file. The only logic which appears in the HTML portion is display logic. In other words, simple error handling, ifs, loops, etc. Basically, the same stuff that you'll find in most templating languages.

My reason for avoiding templating languages is that it's yet another form of syntax that I need to worry about. What's the point? PHP provides more than I need for this purpose.

Meanwhile, you can take a simple MVC approach by separating things:

controller.php

<?php
// some application logic
$data['message'] = 'Hello, World.';

include 'view.php';

exit;
?>

view.php:

<html>
<head>
<title>
A simple 'MVC' view
</title>
</head>
<body>
<p>
<?php

echo $data['message'];

?>
</p>
</body>
</html>

This isn't without its drawbacks and issues. However, if you think you can have complete, clean separation between application logic and display, you're mistaken.

Solution 3

We use a customized code igniter base for MVC and just have logic and layout separated. that doesn't necessarily mean there's no php in our html, just that its not used for logic. It's perfectly okay to loop through a recordset with php code in a template imho, just don't try to talk to business objects and actually do stuff in the layout templates. You could ofcourse also look into something like tal or a million others for the templates if you really want to get rid of all php code there. I'm kinda thinking that's mostly overkill though, unless "insert special circumstance here"

edit fixed typo

Solution 4

In my experience, a lot of PHP development, whether for better or worse, ends up being php files connected to each other through includes that print out snippets of HTML as needed.

Mind though, most of my PHP experience is for more of a "we just need something that works" solution than a "we need the most elegant and efficient solution"

Solution 5

any time I see someone's PHP code online, it's either a small snippet working with a single function or such, or the PHP is full of strings containing HTML (or worse, HTML with PHP interspersed).

Yeah, the general quality of code out there is embarrassing.

Whilst you can go to a full-blown templating engine of your own, that may be overkill and in many cases the limited domain-specific-languages they provide will get in your way, when you could just be writing presentation logic in PHP.

If you want to still be writing normal PHP, but without the spaghetti:

  1. Keep action code at the top of the file or in a different file. Put only application logic here, not any kind of HTML or templating. Any information generated in this stage that needs to be displayed by the template needs to go in a variable to be passed to the templating part, not print​ed out in the middle of a load of business logic.

  2. Take your knowledge of tag-based templating and apply it to PHP. Have a single, correctly-indented hierarchy of code for both HTML and PHP presentation logic, as if you were writing ‘well-formed’ XML (whether or not you're actually using XHTML). Avoid putting HTML in strings at all costs.

  3. Define an easier way of calling htmlspecialchars(), because otherwise typing that all the time is going to be a real pain, and if you aren't typing it all the time you're going to have potentially security-sensitive errors.

To summarise, eg.:

<?php
    // active code here
    // do things
    // put any errors in a $errors array

    // this trivial function would presumably be in an include
    //
    function h($s) {
        echo htmlspecialchars($s, ENT_QUOTES);
    }
?>

<body>
    <?php if (count($errors)!=0) { ?>
        <ul id="errors">
            <?php foreach ($errors as $error) { ?>
                <?php h($error); ?>
            <?php } ?>
        </ul>
    <?php } ?>
    ...
</body>

In the "real world" of PHP programming, what's the preferred method:

Oh, in the real world of PHP programming, the average project has a mishmash of approaches thrown together without any thought. In the real world the code is unmaintainable, bug-ridden, and insecure. You don't want to look at the Industry Standard, because the Industry Standard is to be broken in every way.

Share:
13,524
Brian S
Author by

Brian S

A programmer is a person who passes as an exacting expert on the basis of being able to turn out, after innumerable punching, an infinite series of incomprehensive answers calculated with micrometric precisions from vague assumptions based on debatable figures taken from inconclusive documents and carried out on instruments of problematical accuracy by persons of dubious reliability and questionable mentality for the avowed purpose of annoying and confounding a hopelessly defenseless department that was unfortunate enough to ask for the information in the first place. -- IEEE Grid newsmagazine

Updated on July 22, 2022

Comments

  • Brian S
    Brian S almost 2 years

    I learned PHP by hacking away at phpBB2, even submitting a few mods to their database, which others downloaded and used. (I don't believe phpBB2 is supported any more with phpBB3 out so long now, so the v2 mods database is no more.)

    One of my favorite things about phpBB was their templates system, which let the editor completely separate the HTML and the PHP. PHP files contained PHP: logic, database queries, and activating the templates. TPL files contained templates: HTML, template variables, and specialized HTML comments to allow for conditional or repeating blocks.

    However, any time I see someone's PHP code online, it's either a small snippet working with a single function or such, or the PHP is full of strings containing HTML (or worse, HTML with PHP interspersed). phpBB is the only PHP I've looked at which actually separates the language and the markup language, suggesting to me that few, if any, other PHP codebases do such a thing.

    I'm looking to start working with some PHP again, but this time it won't be a phpBB forum, and it will be on a team. Based on my experience, separation of PHP and HTML is uncommon (please correct me if I'm wrong on this!). However, I'm so used to that dividing line, I hate reading mixed PHP and HTML.

    In the "real world" of PHP programming, what's the preferred method:

    • PHP files with strings of HTML
    • HTML files broken up with PHP blocks
    • PHP and HTML completely separate (I wish?)
    • Something else?
  • Brian S
    Brian S almost 14 years
    This makes a lot of sense, and it explains all the code I see lying around which I hate looking at.
  • Brian S
    Brian S almost 14 years
    I think this exactly the sort of thing I'm looking for to develop in PHP without piggybacking off of phpBB.
  • Robert
    Robert almost 14 years
    Can you point me to source code for a non-trivial project formatted this way? I like the concept but I would like to see how readable it is on a larger scale, and how a lot of specific circumstances are handled.
  • Brian S
    Brian S almost 14 years
    Could you expand on this? How exactly is PHP a solution to separating PHP and HTML? And what about an example of your MVC approach? I understand the concept of MVC, but my weekend brain (only turned on halfway!) doesn't have a concept of PHP MVC for separating the logic and the presentation.
  • Brian S
    Brian S almost 14 years
    Thanks for the expanded answer. It looks like your recommendation is similar to the recommendation from bobince?
  • George Marian
    George Marian almost 14 years
    @bobince Yes, pretty much. The motivation for my answer was to warn against using a templating system. There are situations where they can be useful. Say, if you have a separate team dedicated to the front-end. However, if you know PHP and you're responsible for the HTML (or the back-end devs have to touch it a lot), I think templating systems are generally overkill. Good coding practices can achieve the same thing without an extra layer of processing.
  • Brian S
    Brian S almost 14 years
    Ok, I understand. The motivation for my question was mostly because I became so used to phpBB's templating, that I simply don't like reading files with mixed PHP and HTML. I think I could handle this level of mixture, though; I think the only significant difference between what I'm used to and your MVC example would be presentation logic, and this route would even be superior (at least to phpBB2) if the presentation logic started to get particularly complicated.
  • George Marian
    George Marian almost 14 years
    @Brian S Note, if you remove the calls to include and exit, this can be done in one file. That's the approach I typically use for relatively simple pages.
  • Amit Patil
    Amit Patil almost 14 years
    No, I can't. I have yet to meet a publically-available PHP project whose templating isn't a maze of twisty little echo-HTMLs, all alike.