How to handle HTML in code

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
roowie
Forum Newbie
Posts: 2
Joined: Thu Feb 28, 2008 2:48 pm

How to handle HTML in code

Post by roowie »

First off I will start with a short introduction of myself since I'm new to this board. I'm a twenty year old guy from Sweden with three years of experience in PHP programming. I'm currently working as an application engineer for a bigger website.

I recently started to think about the problem (from my view) in printing HTML from PHP. What do I mean when I say this is problem? Well, we all know that reading and writing HTML code in a PHP document is a pain. And the indentions and whitespace will look really awful and be out of control when executed.

So how can we solve this? There are several templating systems out there, but they have too much rules and are often big and complex. I want to write all my loops and code in PHP. My idea was to create a couple of functions to help create HTML tags and then keep track of indention and automatically handle line breaks. The functions will be written in C as a Zend module. Here is some example code:

Code: Select all

<?php
    tag("body");
        tag("div", array("class" => "info"));
            text("p", "If you want to create a new account, please " . hyperlink("click here", "/create", "Create a new account"));
        tag();
 
        tag("div", array("class" => "login"));
            form("login", "/login.php", GET);
                box("uid", "134680", HIDDEN);
                box("key", "aNmMAF", HIDDEN);
 
                box("username", NULL, TEXT);
                box("password", NULL, PASSWORD);
 
                img("/images/validate.png", "Type this text in the box below", 50, 200);
                box("validate", NULL, TEXT);
 
                button("Submit form", SUBMIT);
            form();
        tag();
    tag();
?>

Code: Select all

 
<body>
    <div class="info">
        <p>If you want to create a new account, please <a href="/create" title="Create a new account">click here</a></p>
    </div>
    <div class="login">
        <form name="login" action="/login.php" method="GET">
            <input type="hidden" name="uid" value="134680" />
            <input type="hidden" name="key" value="aNmMAF" />
            <input type="text" name="username" value="" />
            <input type="password" name="password" value="" />
            <img src="/images/validate.png" alt="Type this text in the box below" height="50" width="200" />
            <input type="text" name="validate" value="" />
            <input type="submit" value="Submit form" />
        </form>
    </div>
</body>
 
I have made a functional copy of this as a Zend module but have discovered a problem:

In my example we had a function named text() with a argument executing another function:
text("p", "If you want to create a new account, please " . hyperlink("click here", "/create", "Create a new account"));

PHP will first execute hyperlink() and append its output to the string and then execute text(). As mentioned earlier my functions automaticly indents and add line breaks. This is a problem - I don't want a indention or line break inside my paragraph. One way to solve this problem is to add an extra argument: hyperlink("click here", "/create", "Create a new account", TRUE);. TRUE will tell the function to not indent or break line, but this is not a neat solution.

So my question is, can I in some way check if my function is passed as a argument to another function?

I'm glad for any toughts or ideas about all of this.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: How to handle HTML in code

Post by alex.barylski »

Google for bTemplate...

It's a native template engine and you can avoid using messy functions like body() to output HTML.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: How to handle HTML in code

Post by pickle »

I hate to make a comment like this when someone appears to have put so much effort into something - but I think this is a poor approach.

Consider the overhead for this approach as opposed to using a template engine (I'll use Template_Lite as an example because that's what I use):

For a simple page like this, you've got 17 function calls. There's obviously going to be some "session-like" variables as well, so you know what tag to close when you call tag() without variables. To change any of the variables, you'll still have to poke through a page's worth of function calls, just to change some variables - so you haven't really simplified anything from a maintenance perspective.

Putting this into a template is actually quite trivial. You'd have 1 function call (again, using Template_Lite as an example, I'm not sure how other engines would be used) to set all the variables (such as your uid, key, validation image URL), and 1 function call to say what template to display. The template for this case would pretty much just be plain HTML with a few variable substitutions - no control structures to muddy the waters.

Putting your display logic in a template file will also allow you to have different indentation in the two files & not let them muddy each other.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
roowie
Forum Newbie
Posts: 2
Joined: Thu Feb 28, 2008 2:48 pm

Re: How to handle HTML in code

Post by roowie »

I've realized I spent so much time with this yesterday so it all lost its purpose. :)
Played around a bit with bTemplate and I've underestimated the power of separating View and Control layer.

But of course I'm must defend my idea: :)

My benchmarks were not that bad, 10000 requests with Apache's benchmark gave the same result as with echo. I've not tried xdebug.

All you really need is three functions:

Code: Select all

tag([tag], [array]);          => <tag> or </tag>
mini(tag, [array]);           => <tag />
text(tag, text, [array]);     => <tag>text</tag>


The variable of open tags are handled inside C in a linked list, so it's pretty fast and simple.

Back to reality and a conclusion, my solution will not separate code from design and it's going to be alot of function calls.
Well, thanks for the wake up and a great board.
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Re: How to handle HTML in code

Post by Zoxive »

I also don't see the point in having functions for html. You end up adding even more text then needed to write the html when you have to call the function with multiple parameters.

Code: Select all

<?php 
tag('input',null,array(
  'type'  =>  'text',
  'name'  =>  'Testing',
  'value' =>  '',
  'title' =>  'Editing Testing',
));
//vs
?>
<input type="text" name="Testing" value="" title="Editing Testing"/>
The overhead alone, is enough for me to dislike it, but now I have to more complicated calls?
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: How to handle HTML in code

Post by alex.barylski »

roowie wrote:My benchmarks were not that bad, 10000 requests with Apache's benchmark gave the same result as with echo. I've not tried xdebug.
Not bad, perhaps, but calling that many functions is certainly slower than inlined HTML.

Everytime you call a function there are *at least* two things which must occur:

1) The code must push the current context onto a stack (save state) and 'jump' to the location of the called function.
2) When the function returns the stack must unwind and code must jump back to the original location (restore state).

This is an incomplete description but the idea is every function incurs a save state - restore state and what exactly occurs during that period is usually determined by the function call convention(s) -- two common conventions are:

- __cdecl most commonly used in C and I assume PHP as it supports 'variadic' functions.
- __stdcall comonly used in the Windows API.

I would assume that a function call in PHP is a relatively expensive operation, especially when called on an object, because PHP objects are *always* polymorphic -- meaning they require an additional lookup table (vtable) to locate the function call.

The point is, in PHP, a function is not something you want to overuse for no reason. Like wrapping 'echo' inside a function:

Code: Select all

function myprint($value)
{
  echo $value;
}
Definetely use a template engine, develop your own from bTemplate as I suggested and save yourself a headache and wasted clock cycles. :)

Cheers :)
Post Reply