Why you don't want to mix PHP and HTML directly.

rubberman 3 Tallied Votes 2K Views Share

PHP is an object-oriented language, based (loosly) upon C++. It has classes, methods, member variables, and all that other good stuff. It runs on your web server, not in the client, but the HTML, JavaScript, and other stuff such as CSS blocks that it emits with its output commands are run on the client.

The purpose of this tutorial is to explain why you don't want to mix your PHP and HTML, JavaScript, etc. One reason is if you do that, it becomes pretty much impossible to debug. Another is that is it inefficient.

  1. Use classes and methods to build up your output HTML strings from the logic, passed $_GET, $_POST, and other global variables, and ONLY output them once they are completely formed.
  2. This allows you to recursively call (include) the same PHP code from forms that are created and output, providing you the capability to get some really complex stuff working that would be impossible otherwise.
  3. You can better validate passed variables, SQL query predicates, etc.
  4. If needed, you can emit debug data when inside your class member functions that would not be visible if you tried to do that when inside a JavaScript block of code.

So, don't mix PHP and HTML, etc. Build your output strings inside your PHP class functions and only output them once you have finished.

Example (mostly pseudo code):

<?php
    class MyClass {
    public
        $output = '';
        $debug = false;
        function __construct() {}
        function __destruct() {}
        function display()
        {
            echo "$output";
        }
        function addToOutput($aString)
        {
            if ($debug === true)
            {
                // Escape tags in $aString so it won't be interpreted as HTML commands
                // by the client - just as text.
                $massagedText = stringify($aString);
                echo "MyClass::addToOutput - $massagedText<br/>";
            }
            $output .= $aString;
        }
    }
    MyClass mc = new MyClass;
    mc->addToOutput('Some HTML code here to append to $output.');
    mc->display();
?>

Inside the constructor, you can evaluate the $_GET, $_POST, and other variables (or arguments if you wish) to begin building the output string which can be as complex as you wish. This methodology also allows you to add forms, tables, CSS blocks, JavaScript and such as needed, simply by calling mc->addToOutput($someString). When the mc->display() method is called, all that stuff is sent to the client as a single message, and executed/displayed there as appropriate. Because there is only one message from server to client, it is much more efficient (faster) than many small messages.

So, this allows you to use the server for what it was designed for - to serve data to the client, and allows the client to do what it was designed for - to display data and take user input to send back to the server for further processing.

Member Avatar for diafol
diafol

Big fan of separating php/html. So you are suggesting that all html output is produced via php classes as opposed to having template files? Or would you use both?

veedeoo 474 Junior Poster Featured Poster

I am also a big fan of the separation of business logic and presentation logic. In fact, I have attempted to create a very simple template engine that can run simple html rendering from a parent text file serving as the main template file.

For the sake and for the support of the above tutorial, please allow me to contribute something I think will be helpful to others.

We can easily achieved dynamic templating without even creating a multiple template files. However, as the application gets bigger, the server resources becomes the main bread and butter of this method. So, please use this technique sparingly.

This idea came up to me when a friend from github have asked me to contribute on codeIgniter dynamic application creation project. It is something that hasn't been release to this date, but I will modify my codes to prevent any confusion and also in fairness to the person whom I have given the permission to use the snippet.

This is pretty much inspired by the smarty templating engine. The only difference is that this will not compile, but rather deliver the content directly after they are prepared.

Let Say we have an Obejct Oriented written application that will output an array. This array can be any data types. In order to implement or take advantage of the server side doing the lifting, we can change our back-end development perspective a few angles from either the left or the right of the norms. I know people who are in the early stage of their web developing studies or carrier, may have find this response less interesting. However, as you become a well seasoned developer, the feeling of confinement inside the box is sometimes unbearable.

Step One: We create a master template file. We can call this file parent.txt

<!DOCTYPE html>
<html>
    <head>
    </head>
        <body>
            <h2>{{$title}}</h2>

            <p>
            {{$content}}
            </p>

            <p>
            {{$description}}
            </p>

        </body>
</html>

Step two: We create our load_view function save as index.php

<?php

function load_view(){

    $fileContents = file_get_contents("parent.txt");
    $text = array(
                    'content' =>'This is content from the function written by load view',
                    'title' => 'This is title',
                    'description' => 'This is description'

                );

    $theme_syntax =array(
                    '{{$content}}',
                    '{{$title}}',
                    '{{$description}}'
                    );


    $newContents = str_replace($theme_syntax, $text, $fileContents);


        return $newContents;

}


echo load_view();

If we direct our browser to index.php, we get the same result as if the html file really exist as file. Even the source code will look like this

<!doctype html>
<html>
    <head>
    </head>
        <body>
            <h2>This is title</h2>
            <p>
            This is content from the function written by load view
            </p>
            <p>
            This is description
            </p>
        </body>
</html>

The beauty of the above is that not only it will meet the suggested method by the tutorial, but it also allow the use of responsive frameworks like bootstrap and foundation.

Thanks for allowing me to post something on your tutorial page :).

mattster commented: That's brilliant! Thanks! +4
rubberman commented: I appreciate the comment and suggestions. Thanks! +12
Member Avatar for diafol
diafol

I've toyed with different templating engines for years and developed some of my own custom solutions. As veedeoo says, performance can take a bit of a hit with simple DIY solutions, whereas the big hitters tend to cache output, making them load ridiculously quickly. Personally I like to see clean html (with placeholders) in html files, e.g.

<p>{{something}}</p>

rather than php generated html as in:

echo "<p>$something</p>";

The former could then be almost independent of the backend language.

So it is often replacement vs concatenation. That's simplistic I know.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

I appreciate any and all comments that help expand upon what I wrote for this tutorial. Writing good web code is not simple or straightforward, and many sites are vulnerable to hacking and malware infections because proper diligence is not applied to the code. Hopefully this thread will help steer web developers in the right direction.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

@diafol
I think both using classes as well as templates have their uses. I haven't yet delved much into templates, so the question is a good one, encouraging me to do some research on that subject. Veedeoo's comment certainly helps in that regard as well.

Member Avatar for diafol
diafol

No prob. I think we've all struggled to find the best solution to the almost inevitable mixing of markup and code. I think the solution often comes from the scope of the project. I'll use templating engines for some, but then spew out php inspired html for others. I think the key is to be consistent within the project itself. MVC design and its offshoots certainly help with maintaining separation, but then again, these approaches are only as good as the restraint, organization and patience of the coder throwing things together in order to meet looming deadlines, heh heh.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

@diafol
Yeah. I've never met a deadline I couldn't exceed... :-)

Member Avatar for diafol
diafol

Heh heh.

Here's a list of some of the templating engines that I've used and that may prove useful for others if you want to use templates to separate html/php

RainTPL: http://www.raintpl.com/
Twig: http://twig.sensiolabs.org/
Smarty: http://www.smarty.net/

There are a growing number of more good ones out there as well. Example the dwoo reboot: http://dwoo.org/

They're all pretty similar.

veedeoo 474 Junior Poster Featured Poster

I think new Dwoo is way better than the 2008 release. This is the second template engine I have learned. I think I even suggested the iterator count to the authors back in 2009 and then they disappeared for a few months to do some major overhaul. I thought they will never come back.

The PSRization looks a little odd though, but I would like to give Dwoo another chance as a CI library.

Jeff_8 0 Newbie Poster

I'm a fan of MVC, which helps in keeping php and html separated. Of course, the particular framework I use--much like others I'm sure--doesn't prevent you from abusing the view and mixing in more than necessary, though.

One particularly useful package that lends itself well to this approach is mpdf. I've had to rewrite large chunks of code over the last couple of years when change requests have included pdf output. After doing these rewrites a couple of times, I've started using this approach for all my code.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

The thing that get's me about template engines is that in order to be as expressive as the language they are written in, they can become quite complex and add another learning curve for the designers.

The developers have to learn the template syntax as well and know how to debug that template engine. This is another layer of complexity on their existing stack.

The former could then be almost independent of the backend language.

Most projects don't need to give the UI the ability to switch backeneds - though it does happen. Also a template is coupling your view to the syntax of the templating engine just the same as it would to PHP.

For example, if you're doing a foreach() loop in the template, you are going to use the templates foreach() like syntax. There is also property resolution ie. -> and [] in PHP objects and arrays, \ for namespaces. Conditional statements, type comparisons etc. that have to part of an expressive templating engine.

If you switch backends the backend has to support that particular template syntax.

It's impossible to totally decouple the view from the backend. To do that you have to move your templating to purely client side. So the decision lies in the needs of the project. I think there is nothing wrong with going pure PHP in the template. This is what PHP was written for in the beginning.

If the project has dedicated designers that don't want to learn PHP then maybe. Templating languages can be simpler to learn for someone totally new to PHP. I'd argue there is more value in learning PHP even for a designer.

The real concern is to separate presentation from business logic as mentioned before. It's quite cheap to rewrite the presentation layer in another language if it's fully separated. It would be more expensive to switch backends and have the backend implement a template engine with the same syntax not to mention expose the same objects to the template.

Gideon_1 15 Junior Poster

what took you so long to post this. You are great!

David_50 13 Junior Poster in Training

When you talk about executing code, php loads the server but ecmascript loads the clients, which is better for scaling. However, you have to cost out the amount of code and supporting data you are shipping, for cpu speed is still much cheaper than bandwidth.

TexWiller 0 Newbie Poster

imho modern php coding follows these best practices:
strong application of mvc pattern with
url rewriting
a router
business logic in classes absolutely no html output from php
in php prepare all data to pass to view(html)
can use a template engine
must use an orm

if you work in team programmers must develop web designers must have capability to modify 'pages' without edit php.

for the sake of simplicity and low learning curve
i suggest you to to give a try to Click Here
Ioften use for rapid prototyping.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.