I have to modify some parts of a large PHP application. The different parts were written, of course, by different people (mostly interns). After looking through the code, I found that there were 2 styles of coding used by the other developers:
The 'PHP is the glue of the Internet' style, mixing html and php, ex.:
[snip]
<tr class="ds_subsubhead_2">
<td colspan="21" align="left"> A <select name="nb_linge" onChange="MM_jumpMenu('parent',this,0)" style="vertical-align:middle"> <option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','9999') ?>" <? if($messagesParPage == '9999') { ?>selected="selected"<? } ?>>Tous</option>
<option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','25') ?>" <? if($messagesParPage =='25') { ?>selected="selected"<? } ?>>25</option>
<option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','50') ?>" <? if($messagesParPage =='50') { ?>selected="selected"<? } ?>>50</option>
<option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','75') ?>" <? if($messagesParPage =='75') { ?>selected="selected"<? } ?>>75</option>
[snip] or
<td <? if((isset($_GET['t1']))&&($_GET['t2']!='ALL')) { ?>bgcolor="#0099FF"<? } ?>></td>
<td <? if((isset($_GET['t3']))&&($_GET['t4']!='ALL')) { ?>bgcolor="#0099FF"<? } ?>></td>
<td <? if((isset($_GET['t5']))&&($_GET['t6']!='ALL')) { ?>bgcolor="#0099FF"<? } ?>></td>
[snip] or even
<script type="text/javascript" src="<?=$_SESSION["path"]?>lib/js/ajax.js"></script>
[snip]
... and the more procedural way, ex.:
[snip]
$output .= '<td valign="top"><form name="form5" method="GET" action=""><select name="m" onchange="this.form.submit()">';
if ( empty($_GET['p']) ) $output .= '<option value=" ">All</option>';
else $output .= '<option value='.$_GET['m'].'>'.$_GET['m'].'</option>';
$query = "SELECT DISTINCT maoie FROM ".$BD."site";
$res = mysql_query($query);
while ( $row = mysql_fetch_assoc($res) ) {
if( !empty($row['maoie']) ) $output .= '<option value="'.$row['maoie'].'">'.$row['maoie'].'</option>';
}
$output .= '</select></form></td>';
$output .= add_more_stuff();
echo $output;
Now, I'm not completely sure that this is a more procedural way to do things, but at least it is different from the previous one. Which one, do you think, is generally better?
I, personally, dont't like 'the glue of the Internet' style.
I would ditch both and code the PHP away from any presentation-layer specific HTML. Otherwise things get very nasty, very quickly for anything bigger than 'Hello World' :)
You are shooting yourself in the foot if you want to modify the code later. I would try and kill off this problem by porting to a proper CMS/Abstract presentation.
Neither look good. I wouldn't want to maintain code in either style. save time later by spending time now cleaning it up properly.
Even something as basic as moving your HTML into externally loaded format strings and running them through sprintf() or similar might be better than the current situation. And you say you have a mix of these coding styles !?!
good luck to you sir!
Both styles should be relegated to the tomb of dynamic internet growing pains. Take a peek through some open source PHP projects to see a good, maintainable coding style in action. Things like http://sourceforge.net/projects/wikipedia MediaWiki show a good mix of HTML-In-Source and separation (although it is not perfect IMHO)
There is a third option: templates. Templates are more readable than glue or random emission of ascii vomit. I just tend to use HEREDOCd strings and str_replace, thus:
$template = <<<TEMPLATE
<html>
<head>
<title>{TITLE}</title>
</head>
<body>
<div id='nav'>{NAV}</div>
<div id='content'>{CONTENT}</div>
</body>
TEMPLATE;
$data = array (
"{TITLE}" => "Page title example",
"{NAV}" => buildNav(),
"{CONTENT}" => buildContent());
str_replace(array_keys($data),array_values($data), $template);
I tend to go for something in the middle. If I'm calling fifteen different functions to generate a select <option>, why not just have one function that does everything and creates the complete markup?
Something like this (completely made up example):
<select>
<?php
foreach (database_query() as $row)
echo gen_select($row)
?>
</select>
and somewhere else
function gen_select($row) {
// do something horrifically complicated with the data (creating some variables to make the output easier to follow
return "<option class=\"$class\">$text</option>";
}
I personally work on a CMS that has the latter version, and I am having a very hard time reading it.
2ndly, model/controller code within view's is a great Italian dish.
Both are horrible (that's the real weakness of PHP in my opinion), but at least the first looks readable.
Problems will eventually arise once conditions (is the request POST? is the data valid?) are added, and it will lead invariably to the dreaded second kind of coding. Try to decouple view and logic: str_replacing is way better than building a string by concatenating one gazillion small pieces.
No offence, but both style is from the late '90-s.
You should seriously consider refactor the system and use a template engine to separate at least the PHP and the HTML code.
Even better if you can separate the "business logic" and the "display logic" part.
I think HTML and PHP should be seperated as much as possible. It makes the whole code easier to read and creates a clear structure. That means for me that PHP should not output HTML, since you can use HTML to do that part...
So I'd also prefer the last example, but with one difference: I think using the bracket-style mixed into HTML makes it very hard to read the code. The if...endif style is the better alternative I think. Also printing HTML with PHP seems unlogic.
I'd do it this way:
<td valign="top"><form name="form5" method="GET" action=""><select name="m" onchange="this.form.submit()">;
<? if ( empty($_GET['p']) ): ?>
<option value=" ">All</option>
<? else: ?>
<option value="<?=$_GET['m']?>"><?=$_GET['m']?</option>
<? endif; ?>
<?
$query = "SELECT DISTINCT maoie FROM ".$BD."site";
$res = mysql_query($query);
while ( $row = mysql_fetch_assoc($res) ):
?>
<? if( !empty($row['maoie']) ): ?>
<option value="<?=$row['maoie']?>"><?=$row['maoie']?></option>
<? endif; ?>
<? endwhile; ?>
</select></form></td>
<? echo add_more_stuff(); ?>
At least this is a bit more logic. Nevertheless things like database interaction should be excluded to somewhere else in your web application. If you seperate the data and the design of your page it gets much clearer.
Nevertheless I think using PHP as a template language is totally fine as long as you only use some replacement variables and simple if-statements.
Related
I want to conditionally output HTML to generate a page, so what's the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework like Smarty?
echo '<html>', "\n"; // I'm sure there's a better way!
echo '<head>', "\n";
echo '</head>', "\n";
echo '<body>', "\n";
echo '</body>', "\n";
echo '</html>', "\n";
There are a few ways to echo HTML in PHP.
1. In between PHP tags
<?php if(condition){ ?>
<!-- HTML here -->
<?php } ?>
2. In an echo
if(condition){
echo "HTML here";
}
With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:
echo '<input type="text">';
Or you can escape them like so:
echo "<input type=\"text\">";
3. Heredocs
4. Nowdocs (as of PHP 5.3.0)
Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP's original purpose was to be a templating language. That's why with PHP you can use things like short tags to echo variables (e.g. <?=$someVariable?>).
There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g. {{someVariable}}).
The primary benefit of using a template engine is keeping the design (presentation logic) separate from the coding (business logic). It also makes the code cleaner and easier to maintain in the long run.
If you have any more questions feel free to leave a comment.
Further reading is available on these things in the PHP documentation.
NOTE: PHP short tags <? and ?> are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option. They are available, regardless of settings from 5.4 onwards.
Try it like this (heredoc syntax):
$variable = <<<XYZ
<html>
<body>
</body>
</html>
XYZ;
echo $variable;
You could use the alternative syntax alternative syntax for control structures and break out of PHP:
<?php if ($something): ?>
<some /> <tags /> <etc />
<?=$shortButControversialWayOfPrintingAVariable ?>
<?php /* A comment not visible in the HTML, but it is a bit of a pain to write */ ?>
<?php else: ?>
<!-- else -->
<?php endif; ?>
Basically you can put HTML anywhere outside of PHP tags. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
The data display itself could be at the bottom of the same PHP file or you could include a separate PHP file consisting of mostly HTML.
I prefer this compact style:
<?php
/* do your processing here */
?>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php foreach ( $something as $item ) : ?>
<p><?=$item?></p>
<?php endforeach; ?>
</body>
</html>
Note: you may need to use <?php echo $var; ?> instead of <?=$var?> depending on your PHP setup.
I am partial to this style:
<html>
<head>
<% if (X)
{
%> <title>Definitely X</title>
<% }
else
{
%> <title>Totally not X</title>
<% }
%> </head>
</html>
I do use ASP-style tags, yes. The blending of PHP and HTML looks super-readable to my eyes. The trick is in getting the <% and %> markers just right.
Another approach is put the HTML in a separate file and mark the area to change with a placeholder [[content]] in this case. (You can also use sprintf instead of the str_replace.)
$page = 'Hello, World!';
$content = file_get_contents('html/welcome.html');
$pagecontent = str_replace('[[content]]', $content, $page);
echo($pagecontent);
Alternatively, you can just output all the PHP stuff to the screen captured in a buffer, write the HTML, and put the PHP output back into the page.
It might seem strange to write the PHP out, catch it, and then write it again, but it does mean that you can do all kinds of formatting stuff (heredoc, etc.), and test it outputs correctly without the hassle of the page template getting in the way. (The Joomla CMS does it this way, BTW.)
I.e.:
<?php
ob_start();
echo('Hello, World!');
$php_output = ob_get_contents();
ob_end_clean();
?>
<h1>My Template page says</h1>
<?php
echo($php_output);
?>
<hr>
Template footer
$enter_string = '<textarea style="color:#FF0000;" name="message">EXAMPLE</textarea>';
echo('Echo as HTML' . htmlspecialchars((string)$enter_string));
Simply use the print function to echo text in the PHP file as follows:
<?php
print('
<div class="wrap">
<span class="textClass">TESTING</span>
</div>
')
?>
In addition to Chris B's answer, if you need to use echo anyway, still want to keep it simple and structured and don't want to spam the code with <?php stuff; ?>'s, you can use the syntax below.
For example you want to display the images of a gallery:
foreach($images as $image)
{
echo
'<li>',
'<a href="', site_url(), 'images/', $image['name'], '">',
'<img ',
'class="image" ',
'title="', $image['title'], '" ',
'src="', site_url(), 'images/thumbs/', $image['filename'], '" ',
'alt="', $image['description'], '"',
'>',
'</a>',
'</li>';
}
Echo takes multiple parameters so with good indenting it looks pretty good. Also using echo with parameters is more effective than concatenating.
echo '
<html>
<body>
</body>
</html>
';
or
echo "<html>\n<body>\n</body>\n</html>\n";
Try this:
<?php
echo <<<HTML
Your HTML tags here
HTML;
?>
This is how I do it:
<?php if($contition == true){ ?>
<input type="text" value="<?php echo $value_stored_in_php_variable; ?>" />
<?php }else{ ?>
<p>No input here </p>
<?php } ?>
Don't echo out HTML.
If you want to use
<?php echo "<h1> $title; </h1>"; ?>
you should be doing this:
<h1><?= $title;?></h1>
Are there any differences between...
if ($value) {
}
...and...
if ($value):
endif;
?
They are the same but the second one is great if you have MVC in your code and don't want to have a lot of echos in your code. For example, in my .phtml files (Zend Framework) I will write something like this:
<?php if($this->value): ?>
Hello
<?php elseif($this->asd): ?>
Your name is: <?= $this->name ?>
<?php else: ?>
You don't have a name.
<?php endif; ?>
At our company, the preferred way for handling HTML is:
<? if($condition) { ?>
HTML content here
<? } else { ?>
Other HTML content here
<? } ?>
In the end, it really is a matter of choosing one and sticking with it.
They are indeed both the same, functionally.
But if the endif is getting too far from the correspondent if I think it's much better practice to give a referencing comment to it. Just so you can easily find where it was open. No matter what language it is:
if (my_horn_is_red or her_umbrella_is_yellow)
{
// ...
// let's pretend this is a lot of code in the middle
foreach (day in week) {
sing(a_different_song[day]);
}
// ...
} //if my_horn_is_red
That actually applies to any analogous "closing thing"! ;)
Also, in general, editors deal better with curly brackets, in the sense they can point you to where it was open. But even that doesn't make the descriptive comments any less valid.
Here's where you can find it in the official documentation: PHP: Alternative syntax for control structures
I think that it's particularly clearer when you're using a mix of ifs, fors and foreaches in view scripts:
<?php if ( $this->hasIterable ): ?>
<h2>Iterable</h2>
<ul>
<?php foreach ( $this->iterable as $key => $val ):?>
<?php for ( $i = 0; $i <= $val; $i++ ): ?>
<li><?php echo $key ?></li>
<?php endfor; ?>
<?php endforeach; ?>
</ul>
<?php elseif ( $this->hasScalar ): ?>
<h2>Scalar</h2>
<?php for ( $i = 0; $i <= $this->scalar; $i++ ): ?>
<p>Foo = Bar</p>
<?php endfor; ?>
<?php else: ?>
<h2>Other</h2>
<?php if ( $this->otherVal === true ): ?>
<p>Spam</p>
<?php else: ?>
<p>Eggs</p>
<?php endif; ?>
<?php endif; ?>
as opposed to:
<?php if ( $this->hasIterable ){ ?>
<h2>Iterable</h2>
<ul>
<?php foreach ( $this->iterable as $key => $val ){?>
<?php for ( $i = 0; $i <= $val; $i++ ){ ?>
<li><?php echo $key ?></li>
<?php } ?>
<?php } ?>
</ul>
<?php } elseif ( $this->hasScalar ){ ?>
<h2>Scalar</h2>
<?php for ( $i = 0; $i <= $this->scalar; $i++ ){ ?>
<p>Foo = Bar</p>
<?php } ?>
<?php } else { ?>
<h2>Other</h2>
<?php if ( $this->otherVal === true ){ ?>
<p>Spam</p>
<?php } else { ?>
<p>Eggs</p>
<?php } ?>
<?php } ?>
This is especially useful for long control statements where you might not be able to see the top declaration from the bottom brace.
I think that it really depends on your personal coding style.
If you're used to C++, Javascript, etc., you might feel more comfortable using the {} syntax.
If you're used to Visual Basic, you might want to use the if : endif; syntax.
I'm not sure one can definitively say one is easier to read than the other - it's personal preference. I usually do something like this:
<?php
if ($foo) { ?>
<p>Foo!</p><?php
} else { ?>
<p>Bar!</p><?php
} // if-else ($foo) ?>
Whether that's easier to read than:
<?php
if ($foo): ?>
<p>Foo!</p><?php
else: ?>
<p>Bar!</p><?php
endif; ?>
is a matter of opinion. I can see why some would feel the 2nd way is easier - but only if you haven't been programming in Javascript and C++ all your life. :)
I would use the first option if at all possible, regardless of the new option. The syntax is standard and everyone knows it. It's also backwards compatible.
Both are the same.
But:
If you want to use PHP as your templating language in your view files(the V of MVC) you can use this alternate syntax to distinguish between php code written to implement business-logic (Controller and Model parts of MVC) and gui-logic.
Of course it is not mandatory and you can use what ever syntax you like.
ZF uses that approach.
There is no technical difference between the two syntaxes. The alternative syntax is not new; it was supported at least as far back as PHP 4, and perhaps even earlier.
You might prefer the alternative form because it explicitly states which control structure is ending: endwhile, for example, can only terminate a while block, whereas if you encounter a brace, it could be closing anything.
You might prefer the traditional syntax, though, if you use an editor that has special support for braces in other C-like syntaxes. Vim, for example, supports several keystrokes for navigating to matching braces and to the starts and ends of brace-delimited blocks. The alternative syntax would break that editor feature.
In the end you just don't want to be looking for the following line and then having to guess where it started:
<?php } ?>
Technically and functionally they are the same.
It all depends, personally I prefer the traditional syntax with echos and plenty of indentations, since it's just so much easier to read.
<?php
if($something){
doThis();
}else{
echo '<h1>Title</h1>
<p>This is a paragraph</p>
<p>and another paragraph</p>';
}
?>
I agree alt syntax is cleaner with the different end clauses, but I really have a hard time dealing with them without help from text-editor highlighting, and I'm just not used to seeing "condensed" code like this:
<?php if( $this->isEnabledViewSwitcher() ): ?>
<p class="view-mode">
<?php $_modes = $this->getModes(); ?>
<?php if($_modes && count($_modes)>1): ?>
<label><?php echo $this->__('View as') ?>:</label>
<?php foreach ($this->getModes() as $_code=>$_label): ?>
<?php if($this->isModeActive($_code)): ?>
<strong title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></strong>
<?php else: ?>
<?php echo $_label ?>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
</p>
<?php endif; ?>
I used to use the curly braces but now a days I prefer to use this short-hand alternative syntax because of code readability and accessibility.
Personally I prefer making it in two seperate sections but within the same PHP like:
<?php
if (question1) { $variable_1 = somehtml; }
else { $variable_1 = someotherhtml; }
if (question2) {
$variable_2 = somehtml2;
}
else {
$variable_2 = someotherhtml2;
}
etc.
$output=<<<HERE
htmlhtmlhtml$variable1htmlhtmlhtml$varianble2htmletcetcetc
HERE;
echo $output;
?>
But maybe it is slower?
I think it's a matter of preference. I personally use:
if($something){
$execute_something;
}
I used to use curly brackets for "if, else" conditions. However, I found "if(xxx): endif;" is more semantic if the code is heavily wrapped and easier to read in any editors.
Of course, lots editors are capable of recognise and highlight chunks of code when curly brackets are selected. Some also do well on "if(xxx): endif" pair (eg, NetBeans)
Personally, I would recommend "if(xxx): endif", but for small condition check (eg, only one line of code), there are not much differences.
I feel that none of the preexisting answers fully identify the answer here, so I'm going to articulate my own perspective. Functionally, the two methods are the same. If the programer is familiar with other languages following C syntax, then they will likely feel more comfortable with the braces, or else if php is the first language that they're learning, they will feel more comfortable with the if endif syntax, since it seems closer to regular language.
If you're a really serious programmer and need to get things done fast, then I do believe that the curly brace syntax is superior because it saves time typing
if(/*condition*/){
/*body*/
}
compared to
if(/*condition*/):
/*body*/
endif;
This is especially true with other loops, say, a foreach where you would end up typing an extra 10 chars. With braces, you just need to type two characters, but for the keyword based syntax you have to type a whole extra keyword for every loop and conditional statement.
I have a sytem where I want to build an HTML table in PHP from data retrieved from a databse.
I've previously used two different methods for creating the HTML and echoing it.
Building a return variable, and echoing at the end of the PHP script:
<?php
$data['category']['parts']; // format of the data
$retval = '<table>';
foreach($data as $category) {
$retval .= '<tr>';
foreach($category as $data) {
$retval .= '<td>'.$data.'</td>'
}
$retval .= '</tr>';
}
$retval .= '</table>';
echo $retval;
The other method is to echo each line as the code comes to it:
<?php
$data['category']['parts']; // format of the data
echo '<table>';
foreach($data as $category) {
echo '<tr>';
foreach($category as $data) {
echo '<td>'.$data.'</td>'
}
echo '</tr>';
}
echo '</table>';
Which of the two methods is more efficient, in terms of processor/memory usage, and also for processing speed?
Is there actually a real difference, rather than just a question of style?
My shot is: whatever you find more readable. Impact on performance is so small that probably you won't see any difference.
However, if you really care, echo should be faster (nothing better than a performance test on your specific scenario) because string concatenation will resize retval multiple times (and this will impact performance).
Even better you should avoid concatenation also in your echo:
<?php
$data['category']['parts']; // format of the data
echo '<table>';
foreach($data as $category) {
echo '<tr>';
foreach($category as $data) {
echo '<td>', $data, '</td>';
}
echo '</tr>';
}
echo '</table>';
Do you want to do better? Just construct your own string builder object (but, honestly, gain is so small that you should seriously consider if worth your effort).
If you want to use kind of a templating to generate your page, I would rewrite your code to something like this.
(this can be in a dedicated file, and just included to display output)
<?php
$data['category']['parts']; // format of the data
?>
include ('templates/theFileIWantToShow.php');
---- snip files here. Processing above, template bellow.
<table>
<?foreach($data as $category):?>
<tr>
<?foreach($category as $data):?>
<td><?=$data?></td>
<?endforeach;?>
</tr>
<?endforeach;?>
</table>
This would offer (imho) best readability when it comes down to large html pages with only a few wildcards.
Advantages:
You get clean html with only a few spots of php in between
You can easily replace the template files without touching the generating code
you can reuse templates. Providing direct output and/or building strings is a mess, when it comes down to reuse the same html-markup for a certain element over and over.
Note that this requires shorttags to be enabled in your php.ini for PHP < 5.4.0.
I am learning php. I see that people recommend to separate html and php or logic and markup. But in some specific occasions I am not sure how to do it. For readability and maintainability I try to put all the php in a separate file but now I have to download a title from a database and the only way I see is to put this with the rest of the html and with this html and php mixed. In this specific case, is there a more clean and organized way? is ok to put this peace of php in the "design" file? can or should I put this php code with the rest of the php?
<?php
include("../../externs/includes/connexio.php");
$result = mysqli_query($con, "SELECT * FROM myTable");
while ($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$title = $row["title"];
$subtitle = $row["subtitle"];
?>
<div class="title" id="<?php echo $id; ?>"><?php echo $title; ?> </div>
<div class="subtitle"><?php echo $subtitle;?> </div>
<br>
<?php
}//end while items
?>
First of all I would recommend to read about MVC (Model-View-Controller), you can start at this Wikipedia article:
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
For a simple case as the one fro you question, your solution is, in my opinion, the best. Anything else would be to add unnecessary complexity.
That being said, I will try to use that simple case and offer one possible way to separate logic from presentation with the hope that some basic concepts will become clear from it.
my_controller.php
include("../../externs/includes/connexio.php");
$result = mysqli_query($con, "SELECT * FROM myTable");
$myList = array();
while ($row = mysqli_fetch_array($result))
{
$myList[] = $row;
}
// Now load the view.
include "my_view.php";
my_view.php
<?php foreach ($myList as $row ) : ?>
<div class="title" id="<?php echo $row['id']; ?>"><?php echo $row['title']; ?></div>
<div class="subtitle"><?php echo $row['subtitle'];?></div>
<br>
<?php endforeach; ?>
As you see, I just took your code and separated it in what would be business logic and presentation.
The idea here is that data to be presented should be generated outside the View. The View should know nothing about how the data was "generated".
In this example, the View only knows about the variable $myList containing the fields: id, title and subtitle. If you ever change databases or decide to fetch data from a file or even a Web service; you would not have to touch the View at all.
At the same time, the controller doesn't care about how the View shows the data. Regardless of the source: database, Web service, file, etc; it will always produce an array containing at least the fields expected by the View.
The next step to MVC would be to move data manipulation from controller to a model. I won't go there in detail, but this is how the controller would look like:
include "my_model.php";
$myList = fetchData();
include "my_view.php;
The fetchData() function inside the my_model.php file would basically do the same as my_controller.php above.
A very debatable and indeed debated issue is whether having any PHP code inside the View is a good practice. Some argue that other templating languages such as Smarty should be used. My opinion is that changing the syntax by adding another language doesn't change the inevitable fact that you need some logic in the View, otherwise you would be unable to introduce dynamism to your applications.
As you feel more comfortable reading PHP code, you will be able to look into the several frameworks around and see how they do it. One thing they all have in common is that they all have some logic in the presentation layer, whether it is PHP or something else.
Following are the best practices you can follow while mixing PHP with markup.
(Not a best practice)
1) if for example you have a logic on the top and you wish to generate markup, one not so good way you can do is:
<?php
$query = mysql_query("SELECT id,name FROM table");
while($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$name = $row['name'];
?>
<div>ID:<?php echo $id;?></div>
<div>NAME:<?php echo $name;?></div>
<?php
}
?>
In the above code you have to keep track of the ending curly brace, if your application is complex it can create a problem especially in more then one level of iteration.
2) Good way to do is to make use of PHP tags such as
<?php if(count($array)):?>
<?php foreach($array as $result):?>
<div><?php echo result;?></div>
<?php endforeach;?>
<?php else:?>
<div>NO results found</div>
<?php endif;?>
Your code has no presentation issues but if it is a complex application then you need to follow best practices.
<?php
$array = array();
$query = mysql_query("SELECT id,name FROM table");
while($row = mysql_fetch_assoc($query)):
$array[] = $row;
endwhile;
?>
Outside of PHP tag check the count of $array, if there is count then generate markup.
<?php if(count($array)):?>
<?php foreach($array as $result):?>
<div>ID<?php echo result['id'];?></div>
<div>ID<?php echo result['name'];?></div>
<?php endforeach;?>
<?php else:?>
<div>NO results found</div>
<?php endif;?>
Using this kind of formatting you can achieve pleasing results. Try to separate or avoid mixing too much PHP with markup. If you want your presentation logic to be separated from business logic then I recommend you to use MVC model as it increases readability and maintainability.
Please look at the code below.
require_once("initvars.inc.php");
require_once("config.inc.php");
?>
<?php
if($latestads_count)
{
?>
<div class="latestposts">
<div class="head"><?php echo $lang['LATEST_ADS']; ?></div>
<table border="0" cellspacing="0" cellpadding="0" class="postlisting" width="100%">
<?php
$sql = "SELECT a.*, ct.cityname, UNIX_TIMESTAMP(a.createdon) AS timestamp, feat.adid AS isfeat,
COUNT(*) AS piccount, p.picfile AS picfile, scat.subcatname, scat.catid, cat.catname
FROM $t_ads a
INNER JOIN $t_cities ct ON a.cityid = ct.cityid
INNER JOIN $t_subcats scat ON a.subcatid = scat.subcatid
INNER JOIN $t_cats cat ON scat.catid = cat.catid
LEFT OUTER JOIN $t_featured feat ON a.adid = feat.adid AND feat.adtype = 'A' AND feat.featuredtill >= NOW()
LEFT OUTER JOIN $t_adpics p ON a.adid = p.adid AND p.isevent = '0'
WHERE $visibility_condn
$loc_condn
GROUP BY a.adid
ORDER BY a.createdon DESC
LIMIT $latestads_count";
$res_latest = mysql_query($sql) or die($sql.mysql_error());
$css_first = "_first";
while($row = mysql_fetch_array($res_latest))
{
$url = buildURL("showad", array($xcityid, $row['catid'], $row['catname'],
$row['subcatid'], $row['subcatname'], $row['adid'], $row['adtitle']));
?>
<?php
if($row['isfeat'])
{
//$feat_class = "class=\"featured\"";
$feat_img = "<img src=\"images/featured.gif\" align=\"absmiddle\">";
}
else
{
//$feat_class = "";
$feat_img = "";
}
if($row['picfile'])
{
$picfile = $row['picfile'];
$imgsize = GetThumbnailSize("{$datadir[adpics]}/{$picfile}", $tinythumb_max_width, $tinythumb_max_height);
}
else
{
$picfile = "";
}
?>
<tr>
<td width="15">
<img src="images/bullet.gif" align="absmiddle">
</td>
<td>
<b><a href="<?php echo $url; ?>" <?php echo $feat_class; ?>><?php echo $row['adtitle']; ?></a></b>
<?php if(0&&$row['picfile']) { ?><img src="images/adwithpic.gif" align="absmiddle"><?php } ?>
<?php echo $feat_img; ?><br>
<span class="adcat">
<?php echo "$row[catname] $path_sep $row[subcatname]"; ?>
<?php
$loc = "";
if($row['area']) $loc = $row['area'];
if($xcityid < 0) $loc .= ($loc ? ", " : "") . $row['cityname'];
if($loc) echo "<br>$loc";
?>
</span>
</td>
<td align="right" width="<?php echo $tinythumb_max_width; ?>">
<?php if($picfile) { ?>
<img src="<?php echo "{$datadir[adpics]}/{$picfile}"; ?>" border="0" width="<?php echo $imgsize[0]; ?>" height="<?php echo $imgsize[1]; ?>" style="border:1px solid black">
<?php } ?>
</td>
</tr>
This is one of the code files from an existing project. As you can see, it has html, sql, php all intermixed together... and obviously difficult to maintain.
There are around 55 files of similar size and type in this application.
I want to refactor this code,and below are my objectives for doing so:
1)Easy to maintain.
2)Be able to extend easily by adding additional features.
3)Be able to reuse this code for different but somewhat similar applications.
I have a number of question based on the above facts:
1) Do you think we can refactor this code into an mvc application?
2)If we can. how much time should it take to refactor the whole project(55 files) say, for an expert programmer?
3)Should i reuse the above code, or should i start from scratch with a existing mvc framework?
4)How much time do we need to complete the whole project, in case we go for an existing mvc framework say symfony, zend etc.?
5)This site as per my knowledge until now would run Mysql only(as the current db is done in mysql). Should we allow for data abstraction/data acces layers in the model(supposing there is something that performs better than Mysql, I'm not sure about this)
7)Can we easily refactor the code to include sub-layers for model(data abstraction/access), view(further templates, view logic etc.), controller etc. in case we want to do that in future or would we need to start from scratch?
8)Is mvc the way to go , or is there a better pattern/way than it(supposing the site is intended for hundred thousands of users)?
Yes.
I would say about an hour per file of that size to make sure everything goes smoothly. So 1-2 weeks of solid work.
If this works well, just re-factor. If you really want something new, grab a framework.
An existing framework will probably take longer to duplicate existing functionality (maybe a month). However, you will have a more stable application in the long run (most likely).
There is nothing wrong with MySQL. Use a data abstraction layer if you feel like you will want to switch in the future for some other reason.
There is no reason why you wouldn't be able to re-factor. I have done this recently and it is not all that difficult.
MVC is pretty much ideal. That said, there are many different ways to do MVC. Some good, some better, some terrible.
I think there is no thing like an "mvc application", but the mvc pattern can certainly be used in this application. You could build some data classes that encapsule the various queries and translate the result to an object or arrays of objects. A controller class can grab those results and process them, then feed the processed data to a specific template. That is an mvc like construct that is quite easy to maintain. I'd build some helper classes as well. You don't want to call mysql_query everywhere, because maybe you'll need to use mysqli next year, or maybe even a completely different database.
So, yes, use the mvc pattern, but not only that. Refactor the entire code. Use ready to use libraries where you can (for instance for database abstraction), and spent a great deal thinking about the right way to go before you start building.