views:

288

answers:

8

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?
+5  A: 

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

Burbas
I think this exactly the sort of thing I'm looking for to develop in PHP without piggybacking off of phpBB.
Brian S
+1  A: 

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"

Sushisource
This makes a lot of sense, and it explains all the code I see lying around which I hate looking at.
Brian S
+1  A: 

I prefer to use a template system to minimize the amount of PHP code contained in the HTML files. I really don't see any way to entirely separate PHP from HTML, but I feel that it is sufficient to separate business logic (database) from presentation logic.

My template system is home-baked, but I'm sure you can find a variety that would work by preforming a google search.

Dan D.
+3  A: 

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

Kris
+1  A: 

Based on my experience, separation of PHP and HTML is uncommon

True. But lot of PHP code is written by inexperienced developers. Further, PHP does not encourage, but rather discourage writing good code, and the ability to mix HTML with programming code is one of the examples of this.

If you expect to do high quality code, to be able to easily maintain and extend it, I highly recommend using template engine or something similar. Mixing both has a huge impact on the readability of your code, and will result in something becoming worse and worse over time. Refactoring will be painful, if not impossible.

Now, you have a large choice of the way to separate HTML from PHP

  • The most obvious one is to use an existing layout engine. There are plenty of them, some very well done and with a very low performance impact.

  • You can also write your own engine. It may not be a good idea on a big project (why reinvent the wheel?), but can be a solution either on a tiny project or when you need something very specific.

  • The last way I use in most projects is to build XML from business layer (XML serialization is quite easy in PHP), then to use XSLT to transform this to HTML page. It enables to do websites which are much easier to maintain and more easy to understand, and, by the way, enables to access the website data programmatically (loading XML instead of HTML page) when need. On the other hand, it decreases performance hugely, so is not intended for large websites with thousands of queries per second.

MainMa
+1  A: 

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.

bobince
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.
Robert
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.
bobince
A: 

Joomla uses a template approach.

Phil Pratt-Szeliga
+1  A: 

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.

George Marian
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
Thanks for the expanded answer. It looks like your recommendation is similar to the recommendation from [bobince](http://stackoverflow.com/questions/3220655/preferred-way-to-combine-php-and-html/3220993#3220993)?
Brian S
@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.
George Marian
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.
Brian S
@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.
George Marian