Hi
I want to get some expert comments about following two php snippets
first snippet
<?php
for( )
{
?>
<html code>
<?php
}//loop ends
?>
second snippet
<?php
for( )
echo "<html code>";
}//loop ends
?>
| SitePoint Sponsor |
Hi
I want to get some expert comments about following two php snippets
first snippet
<?php
for( )
{
?>
<html code>
<?php
}//loop ends
?>
second snippet
<?php
for( )
echo "<html code>";
}//loop ends
?>
I would rather see something like this:
But that is just me.PHP Code:<?php
$format = '<tag>%s</tag><tag>%s</tag>';
for () {
printf($format, $argA, $argB);
}
# No closing ?-> oh noes!
#Comment bug





I would use:
PHP Code:<?php
for(/*...*/):
?>
<!-- HTML code -->
<?php
endfor;
?>
Location: Alicante (Spain)... Hot and Sunny...
Texas Holdem Poker Probability Calculator | DNS test
Avatars | English Spanish Translation | CAPTCHA with audio
Email | PHP scripts | Cruft free domain names | MD5 Cracker


why not use heredoc
PHP Code:<?php
for( )
{
echo <<<eof
<tag>hey</tag>
eof;
}
How does that make your feel?


My style is to put business logic at the top of the PHP file. Either by using include/require statements or by using code directly. Then the bottom of the file is presentation logic. In most cases, this is HTML which escapes to PHP when needed. This allows me to read the HTML source code and get a better feel of the page layout. Another advantage is that I can see the page layout in a WYSIWYG editor (should I want to do that).
Just my $0.02...
mikem




Founder/Admin of a pretty decent chat forum
Download free winterboard themes for your iPhone
I run sites powered by vbulletin and one about the HTC Jetstream.
Hey everyone.
I gotta agree with Logic Earth here. If you keep a string as the format, it's faster, more efficient (and it looks better), if you use printf (or even sprintf if you want to store it).
Why would you use HereDoc? It's much easier just to escape quotes - and it somehow looks cleaner to me if you use quotes around it.
Jake Arkinstall
"Sometimes you don't need to reinvent the wheel;
Sometimes its enough to make that wheel more rounded"-Molona





heredoc is great for very long HTML sections and SQL queries. The examples given I assume were short because they were just examples.
I would agree with idea of putting code at the top and then echoing what you need in the HTML below. I find it makes it much easier to troubleshoot and maintain the code that way, if you aren't going to be using templates or more complex OOP structure.



The best way is to separate it into two layers - one for the HTML and another for the PHP that converts it into the web page. Makes things much easier for when you want to reorganise the HTML.
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="^$">




I go with Mike Borozdin's version. The syntax used there is PHP's specific template syntax and is exactly what it's meant for. Separating PHP from HTML is completely pointless IMHO. Separating business logic from view logic is a different story however.
Does anyone have an example where PHP is computed before the HTML? Perhaps a sample code for an entire page?
Thanks!
Sure. Say you have 3 queries for a basic front-page. These are to:Does anyone have an example where PHP is computed before the HTML? Perhaps a sample code for an entire page?
- Fetch the Menu for the site
- Get the content
- Add view count to the site
(p.s. I know 3 queries just for this might be unefficient - its an example)
Ok, so what most people would do is this:
It can be better structured in multiple ways, such as putting the PHP at the top:PHP Code:<?
mysql_query("UPDATE `stats` SET value = value+1 WHERE field='views'");
?><html>
<body>
<div id="main">
<ul id="menu">
<?
$menuQuery = mysql_query("SELECT * FROM `menu`");
while($row = mysql_fetch_array($menuQuery)){
printf("<li><a href=\"%s\" alt=\"%s\">%s</a></li>", $row['url'], $row['title'], $row['text']);
}
?>
</ul>
<div id="content">
<?
$contentQuery = mysql_query("SELECT `content` FROM `content` WHERE `page` = 'Home'");
echo mysql_query($contentQuery, 0);
?>
</div>
</div>
</body>
</html>
There are many other ways, for example keeping all the repeditive code in a top file, stuff like that.PHP Code:<?
mysql_query("UPDATE `stats` SET value = value+1 WHERE field='views'");
$menuQuery = mysql_query("SELECT * FROM `menu`");
$contentQuery = mysql_query("SELECT `content` FROM `content` WHERE `page` = 'Home'");
$menu = "";
while($row = mysql_fetch_array($menuQuery)){
$menu .= sprintf("\n<li><a href=\"%s\" alt=\"%s\">%s</a></li>", $row['url'], $row['title'], $row['text']);
}
$content = mysql_query($contentQuery, 0);
?>
<html>
<body>
<div id="main">
<ul id="menu">
<? echo $menu; ?>
</ul>
<div id="content">
<? echo $content; ?>
</div>
</div>
</body>
</html>
Hope that helps.
Jake Arkinstall
"Sometimes you don't need to reinvent the wheel;
Sometimes its enough to make that wheel more rounded"-Molona
It does thank you. I want to make the switch over to this coding style, but the pages I work with are much more complex and trying to imagine how it will handle.
For example a page with:
- navigation menu at the top
- login//user info on the left
- list of new topics on the right
- query and play a video on the middle
- list a bunch of user comments on the video
- fetch random site news on under the comments
Are we to store all of this content into PHP strings at the top of the page? I imagine it will become hard to follow if there are 2 variables initiated at the top and then try to follow them down the page...
nope - this is where OOP comes in.
I use the factory design pattern, which is exceptionally handy when it comes to modules, etc. Maybe you want to check it out:
http://www.sitepoint.com/forums/show...7&postcount=10
That's what I use for the back-end of my site, and it means whenever I change design, I just change template.html and style.css - and it, just works.
The way I do it means it's easily expandable. Heck, i've reused that code twice and all I need to do is create a design, link it to that, add menu items and I'm done. If I want to expand, it's easily done, I'm now even creating a blog add-on for it, and I've already made a portfolio extention.
Apart from being able to expand it, it's also much easier to read, it separates files, and it's also benchmarked faster than procedural coding (on PHP 5).
Jake Arkinstall
"Sometimes you don't need to reinvent the wheel;
Sometimes its enough to make that wheel more rounded"-Molona
You know of all the solutions presented so far they generally require HTML in the business logic, or PHP in the presentation logic. That would limit the developer to using the output from the business logic (easily syllable I know), or going into the business logic and changing the output.
If you want to increase the complexity a bit you could have the developer send a function the HTML to use in the loop so neither person need's the other to do their job, and the designer has full control over presentation.
In your business logic function:
And in your presentation logicPHP Code:<?php
// The function to be called from the view
function showMembers( $html, $pmUsername, $pmBlurb ) {
// Create an array for the place markers
$placeMarkers = array( $pmUsername, $pmBlurb );
// Your loop (which you'll need to set up according to your needs)
for ( $i = 0; $i < 5; $i ++ ) {
/* It's assumed that you'll get the required information in the loop (maybe a database
* query, or looping through a file, etc.
*
* Just note that the replace works based on position, so make sure
* you add the info in both arrays in the same order.
*/
$input = array( "Average Joe" . $i, "This is a blurb" . $i );
// Show the formatted info
echo str_replace( $placeMarkers, $input, $html );
}
}
?>
Granted it's a bit of a big function call, but it keeps the design elements in the designers hands and formats the info.PHP Code:<h1>Members Demo</h1>
<?php showMembers( "<tr><td colspan='2'><hr /></td></tr>
<tr><td>{username}</td><td> </td><td>{blurb}</td></tr>", "{username}", "{blurb}" ); ?>
Just a note on usage : I used the example of member info to illustrate a possible scenario in which you may need to use a loop to display data.
in the function to call the formatted data from the loop there are at least two arguments: the markup, and one or more place markers (which are used to identify the location to insert data)
If your loop needs more information just add more placemarkers to the placemarker array and another argument to the function signature for each additional placemarker.
It should be easy for you to customize.
P.S. Also, to give you a direct answer about your origional question: both methods do exactly the same thing with one minor difference.
The first way won't show any PHP in the HTML output, and you don't need to worry about escaping strings. You can put most anything in there wihtout affecting the PHP script.
The second way will echo the HTML as if it were a PHP string. So that means it may also echo a variable should you have one in your HTML. It may also cause an error if your HTML has the same quotes as your string, so you have to escape them (just note that the function I posted suffers from these drawbacks).
Overall I'd say the first way is less work if you're planning to mix your HTML and PHP.


I also do as Mike B does in template files. The colon and endforeach/endif/etc syntax makes things clearer when mixed with HTML than curly braces. A separate templating language just wastes time.
17-29% of paid ad clicks are fraudulent. Get protected with Improvely, your online marketing dashboard.
→ Conversion tracking, click fraud detection, A/B testing and more.





Sometimes the point of a template system isn't to save time. Rightly or wrongly, our designer is a little scared of PHP. She's a good designer, and that is what we pay her for after all. Using templates, lets her do what she does and lets me do what I do. For less complex projects we can use includes or code at the top or includes in various places in the HTML.
I am all for doing MVC where it can be done, or at least TRYING to separate business logic from presentation. I am no different than anyone else here, I like to be able to quickly scan code, understand it, and modify it if necessary with a minimum of time. I don't however believe that applying principles of DESKTOP program design, always applies to the web. If for no other reason than that the presentation is not normally done programmatically, but done with a document format.
A document format complex enough, that constructing it with an API is sometimes overkill and much too verbose. For small projects you need to be able to mix the document with the code in some ways sometimes.
Then you have CMS systems that put together pages in blocks, for the sake of customization and ease of use for non-technical users.
There is a misunderstanding about template systems such as Smarty. Though you can certainly set it up to do so, Smarty doesn't replace placeholder values and other tags in a tpl file with values you assign, every time you request a page. That may be the way some systems work, but Smarty compiles templates into the very kind off mixed PHP/HTML pages that everyone is discussing here.
As far as being able to remember values that you set in logic code at the top of a page or in an include, when you get down into the HTML below. I may be getting old, and I don't know about anyone else here, but I don't have any problem with that. I don't know how you could expect to do a complex OOP project, or any other project if your memory about what you are doing in your code, wasn't any better than that.
Last edited by Hammer65; Oct 21, 2007 at 10:43.
The crap thing with having HTML sections in your code is that the HTML section is echoed automatically rather than returned.
Location: Alicante (Spain)... Hot and Sunny...
Texas Holdem Poker Probability Calculator | DNS test
Avatars | English Spanish Translation | CAPTCHA with audio
Email | PHP scripts | Cruft free domain names | MD5 Cracker


17-29% of paid ad clicks are fraudulent. Get protected with Improvely, your online marketing dashboard.
→ Conversion tracking, click fraud detection, A/B testing and more.
Exactly - which is why I store output HTML in files.
In fact, a maybe better approach would be to store all the HTML modules you use in a database, which would completely save the need for any HTML in business logic. (I think).
For example, if you had a simple shopping cart, you could have the following rows in the table to show it:
CartHeader
CartRowCode html:<table> <tr><th>Product Code</th><th>Item Description</th><th>Price</th></tr>
CartFooterCode html:<tr><td>%1$s</td><td>%2$s</td><td>£%3$s</td></tr>
(Maybe that's a bit of a long-winded approach - it's an exampleCode html:</table>)
Then you could use the following:
it was a bad example, but if your that desperate to separate logic from HTML, it works.PHP Code:<?
$getHtml_Top = mysql_query("SELECT html_output FROM html WHERE name='CartHeader'");
$getHtml_Row = mysql_query("SELECT html_output FROM html WHERE name='CartRow'");
$getHtml_Bottom = mysql_query("SELECT html_output FROM html WHERE name='CartFooter'");
$top = mysql_result($getHtml_Top, 0);
$row = mysql_result($getHtml_Row, 0);
$bottom = mysql_result($getHtml_Bottom);
echo $top;
foreach($_SESSION['cart'] AS $item){
printf($row, $item, getDescription($item), getPrice($item));
}
echo $bottom;
Jake Arkinstall
"Sometimes you don't need to reinvent the wheel;
Sometimes its enough to make that wheel more rounded"-Molona
But if you're not careful then you could end up with template files like Mamboserver. Their the most horrible thing I've laid eyes on.I also do as Mike B does in template files. The colon and endforeach/endif/etc syntax makes things clearer when mixed with HTML than curly braces. A separate templating language just wastes time.
Bookmarks