简体   繁体   中英

PHP logical coding style

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">&nbsp;A&nbsp;<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM