SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Enthusiast
    Join Date
    May 2012
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,608
    Mentioned
    24 Post(s)
    Tagged
    1 Thread(s)
    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.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,155
    Mentioned
    14 Post(s)
    Tagged
    0 Thread(s)
    The bare minimum to separate PHP from HTML would look something like this:

    The PHP:
    PHP Code:
    <?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:
    PHP Code:
    <!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>
    "First make it work. Then make it better."

  4. #4
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,052
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    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.
    The only code I hate more than my own is everyone else's.

  5. #5
    SitePoint Enthusiast
    Join Date
    May 2012
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Jeff Mott View Post
    The bare minimum to separate PHP from HTML would look something like this:

    The PHP:
    PHP Code:
    <?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:
    PHP Code:
    <!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>

  6. #6
    SitePoint Enthusiast
    Join Date
    May 2012
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Jeff,

    Great, straightforward example.

    Thanks

  7. #7
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    I imagine you are referencing your thread about how to keep track of 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).
    Quote Originally Posted by Chris Coetzee
    I believe all programmers found themselves caught in this situation at least once… the dreadful “spaghetti mess” where you’ve lost track of logical flow in your code and you’re doubtful that your final output will be accurate, you’re also getting increasingly frustrated with working on the code because A is no longer A, but looks like B.
    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 Clean Code 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:

    PHP Code:
    $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:

    PHP Code:
    $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.

  8. #8
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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 Clean Code 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


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •