Page 1 of 1

PHP best coding practices

Posted: Thu Mar 18, 2010 3:51 pm
by karozans
Hi everyone. I have inherited a very large PHP site. Over the years this site has become speghetti code. On most of the pages this is what has happened.

Code: Select all

 
<?php
     200 lines of php
     .
     .
     .
?>
 
500 lines of javascript
200 lines of HTML
 
<?php
         while(true)
         {
?>
              200 more lines of HTML inside the php loop
              .
              .
 
             <?php
                    if(true)
                    {
             ?>
                            more HTML code inside php if
                            .
                            .
                            .
             <?
                     // close for if
                     }
             ?>
          
              yet more HTML
   <?php
    // closing bracket for while loop
    }
    ?>
 

As you can see this is becoming a nightmare to manage.

Tell me. Is there a dissadvantage to writting these pages in PURE php?

Then when I need to print out HTML or Javascript, simply use print() statements or echo's?

I know that maybe it puts a little more calculation time into the server but the code is so complicated it is hard to maintain it.

Also most IDE's that I have used cannot parse PHP, javascript, and HTML all on the same file. So now I cannot use code formatters and such. And I don't get color coding.

So is it bad to write pages in pure PHP???

thanks

Re: PHP best coding practices

Posted: Thu Mar 18, 2010 4:29 pm
by Benjamin
The amount of time required to complete refactor the code base may not be practical. Also, PHP should not be used to output html.

Correct:

Code: Select all

 
<?php while ($n): ?>
    <tr>
      <td>....
    </tr>
<?php endwhile; ?>
 
Incorrect:

Code: Select all

 
<?php
while ($n) {
    echo "<tr>\n";
    echo "  <td>....\n";
    echo "</tr>\n";
}
?>
 
Without seeing the code base I think the best solution is to break down the components into pieces and start the process of decomposition. Specifically, large blocks of html can be moved into separate files and included where required in order to help you understand the logic flow.