Separating HTML from PHP

Hi All,

I am fairly new to both PHP and programming, but I am making good progress in learning the basics and some best practices (Sitepoint has helped a bit with that). A couple days ago a veteran here - Cups - suggested separating HTML from PHP. This was a different topic, but I was asking about how to get a form to display the way I wanted it to. One of the byproducts that Cups noticed was what I think some PHP veterans call “spaghetti code”
The code mixed PHP and HTML in such a way that it lead to some ugly looking echo statements that I think are hard to code and prone to mistakes. The suggestion was made to “separate HTML from PHP” which I think is great piece of advice, but I would like to ask the experts how they would go about this. I know the answer generally given is to use the MVC model and a good framework. My question is, short of that, what else can be done?
This is a wide open question and has been asked before, but I would love even more feedback.
Thanks ahead for any suggestion

Take a look at http://www.smarty.net/ where you will find a popular templating library that takes care of the separation for you. Even if you don’t decide to use it you will still get ideas as to how it is done.

The bare minimum to separate PHP from HTML would look something like this:

The PHP:

<?php

$link = mysql_connect('localhost', 'myuser', 'mypassword');
mysql_select_db('blog_db', $link);

$result = mysql_query('SELECT id, title FROM post', $link);

$posts = array();
while ($row = mysql_fetch_assoc($result)) {
    $posts[] = $row;
}

mysql_close($link);

// include the HTML presentation code
require 'templates/list.php';

The HTML:

<!doctype html>
<html>
    <head>
        <title>List of Posts</title>
    </head>
    <body>
        <h1>List of Posts</h1>
        <ul>
            <?php foreach ($posts as $post): ?>
                <li>
                    <a href="/read?id=<?php echo $post['id'] ?>">
                        <?php echo $post['title'] ?>
                    </a>
                </li>
            <?php endforeach; ?>
        </ul>
    </body>
</html>

You don’t need some bloated framework to learn to separate out display logic. All you really need to do is start teaching yourself to only ever display data within HTML avoiding logic. A good example would be making sure that data derived from the db comes before the HTML. You would than collect that into an array and display it with a loop within the HTML. Some PHP is fine. The thing you really need to eliminate is logic as much as possible. Prepare all data before displaying it. Exactly what Jeff Mott showed as an example.

Hi Jeff,

Great, straightforward example.

Thanks

I imagine you are referencing your thread about [how to keep track of variables](http://www.sitepoint.com/forums/showthread.php?876664-Tools-thoughts-to-help-with-tracking-variables .), replies there dealt with many things, including (from my side) naming conventions for variables, tables and such.

Yesterday you posted some code and I replied with another idea on the ideal proximity of variable declaration and use.

You mention spaghetti code, and yes, although quite well defined on wikipedia in PHP circles it takes on a slightly different guise – from what I have understood it to mean anyhow and I think we have to be careful here.

Chris Coetzee starts off his blog post How to avoid spaghetti mess code with the following statement before suggesting the tools you should be using to avoid this (frameworks etc).

I like that definition and to me, avoiding spaghetti code does not mean simply “use a template”.

However the title of this post is “Separating HTML from PHP”, and yes certainly using a template is the most obvious way to achieve that.

I hold that it is possible to have SQL, PHP and HTML all in one file and it be easy to follow and be very obvious in its intent and implementation and it not to be spaghetti code.

It is possible to write spaghetti code as Chris Cotzee defines it even when using templates, and now what is more you will have to deal with the extra complexity of having code over multiple files, probably in different folders.

I am not saying templates are either good or bad but that their use might depend on your situation and does add some complexity. Done wrongly that will create spaghetti code so that is something you have to plan carefully for.

There are other simple disciplines which can make your code easier to follow too and most of what I spout about naming conventions and code proximity etc I learned from [google]Clean Code[/google] by (Uncle) Bob Martin (kindly given to me by another SP guru btw).

I nod when I read @oddz; comment because it reminds me of my own reaction when I first took time out to discover MVC, Frameworks and n tier layers etc, that when I got back to my own (spaghetti) code I naturally started separating SQL and HTML from my PHP (spaghetti code in even more files … ;))

Its not as easy to say do not mix 3 languages in the same file, but what you can do is start to split the files containing mostly database access code (or xml access code if you will) from what ought to probably be in a template.

Prior to adopting a known framework these two tricks might help you start to start thinking about “separating concerns”:

Write SQL statement like this:


$qry = "SELECT this
            , that
            , the_other
            FROM mytable 
            WHERE my_condition = 1
            LIMIT 0, 30";


// rest of your stuff

So that your SQL really jumps out at you (plus the lines of select columns can be copied/pasted, easily added/removed, easily counted etc).

This will make you super-conscious of how much SQL you have dotted around your code, and easier to locate and refactor out later.

Write your html output like this at the end of the file if you can, using the heredoc syntax:


$str = <<<EOD
Example of string with a $widget->name
spanning multiple lines
using heredoc syntax.
EOD;

// then

echo $str;

Then you can likewise, easily pull that out into a template when all tee’d up.

There does not have to be a “big bang” where spaghetti code is gone, and you have fully separated concerns - but you can gently and resolutely pry the pieces apart over time.

There are other simple disciplines which can make your code easier to follow too and most of what I spout about naming conventions and code proximity etc I learned from [google]Clean Code[/google] by (Uncle) Bob Martin (kindly given to me by another SP guru btw).

I know that this is an old post, but thanks for the recommendation for this book. I took a look and ordered it (but not on the kindle since that version is apparently crap). I work in science so I work with a lot of people less interested in “wasting their time” with coding books, so my bookshelf is full of these sorts of books. That way I have pointers on hand when they want help and I can point to specific methods of making their code easier to work with, even if they don’t want to take the time to read a book on it themselves.

Cheers,
Thanks