PHP best coding practices

Ye' old general discussion board. Basically, for everything that isn't covered elsewhere. Come here to shoot the breeze, shoot your mouth off, or whatever suits your fancy.
This forum is not for asking programming related questions.

Moderator: General Moderators

Post Reply
karozans
Forum Newbie
Posts: 8
Joined: Mon Sep 15, 2008 5:14 pm

PHP best coding practices

Post 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
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: PHP best coding practices

Post 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.
Post Reply