Home      Technologies      Contact Us  
Date: Sun Feb 01, 2004 5:08 pm
Topic: Article 8 - PHP Basics, formatting and layout
This article will be a basic intro into the style of programming that I like to use when 
programming PHP programs, and what I like to see when looking at other code.
Firstly turning PHP start and end tags (scriptlets). Please use the only.. don't use the
<?php on variable.. Every time I see this, it makes me think that someone is still stuck 
in the PHP3 world, and when PHP5 is just on the horizon it's quite annoying. Also please 
do not use <% %> which are ASP/JSP scriptlets. Also, feel free to embed these tags 
inside your code, some people think you can only use these tags at the top and 
bottom of your scripts, but using them inside your scripts can often make things much 
easier. I will show an example further down the article.
Secondly indenting/spacing. I use 2 spaces for all intending, not 4 spaces, or a tab 
character. God do I hate the tab character. I always run into trouble with that when 
dealing with people who have been working on the window platform with various IDE's 
(integrated development environments). Alot of those programs use a tab to format 
their code, and when I'm using pico or vi to edit code, it becomes a pain, so be sure 
to use 2 spaces. If you cannot distinguish what lines up with what over 2 spaces, you 
need to consider another line of work.
Line wrapping. Bottom line, don't do it! I really hate opening up a file a seeing lines 
that go right off the end of the screen. I typically work on linux using pico and have a
lot of horizontal space for viewing code:
	
Code/Quote:
root@insomnia:~# set | grep COLUMNS
COLUMNS=125
	
125 characters wide is pretty big.. So if you can't fit your code on 1 line, break it up 
nicely.. A typical scenario is for long SQL queries. Instead of just pasting it all into 1 
line that goes right off the screen, use this format:
	
Code/Quote:
<?
$SQL  = "select work_order.id as id, wo_st_link.date_stamp as uploaded, ";
$SQL .= "count(document.id) as docnum, ";
$SQL .= "floor((unix_timestamp(now()) - ";
$SQL .= "unix_timestamp(wo_st_link.date_stamp)) / 60/60) as sinceul ";
$SQL .= "from work_order, wo_st_link left join document on ";
$SQL .= "document.work_order_id = work_order.id ";
$SQL .= "where work_order.owner_id = " . $USER->getID() . " and ";
$SQL .= "work_order.id = wo_st_link.work_order_id and ";
$SQL .= "wo_st_link.status_id = 7 and ";
$SQL .= "wo_st_link.date_stamp like '" . $showDate . "%' ";
$SQL .= "group by work_order.work_order_id desc";
?>
	
You don't need to understand what the above query does, but more importantly 
see the formatting, see that it is easy to read, modify and extend the query. And 
that when the query embeds external variables into the query, it clearly stops the 
string, and uses the "." operator to link the variable to the string.
Commenting... One line comments are always done using //, whereas multi-line 
comments are done using the /* */ syntax. What I like to do in development, is 
at the top of larger files that will require alot of work is put something like this:
	
Code/Quote:
<?
/*
** TODO **
- add methods to update product inventory
- fix this...
- modify that...
/*
?>
	
Basically so that when myself of someone else goes to work on the file they 
have a good idea of what needs to be done.. And you know when the script 
is almost done when the TODO list is empty.
Formatting for "if" constructs.. I have seen alot of different formats and have 
myself changed formats over the years. I have finally settled on what I think 
is the best formatting for handling "if". Always put the opening bracket on the 
line with the "if" condition .. and the closing bracket on it's on line, horizonatally
lining up with the start of the "if" condition. If you are going to extend "if" and 
use "else" put the "else" and the opening bracket for it on the same line. Also, 
put a 1 line comment in each area, so that someone else reading the code can 
understand what will happen based on the condition.. See the example below:
	
Code/Quote:
<?
if (!isset($_GET["id"])) {
  // We didn't recieve a HTTP GET variable for this request, show the news summary
  include("news_summary.php");
} else {
  // We recieved a HTTP GET variable, try and show the news detail for this id
  include("news_detail.php");
}
?>
	
In the example above, depending on how the script was called 1 of 2 actions 
would occur. If someone called the script with the URL: http://server/new.php .. 
They would recieve the news summary, basically a list of all the news items for 
the site, on that page each summary item would have a HREF link to the same 
page but specifying the HTTP GET variable "id". So when the page gets called 
with the URL: http://server/news.php?id=1 .. The page would try and load up 
news item 1, and display it in detail.
Now for a moment to use a similar example of "if" and "else" and using PHP's 
start/stop tags to make things more readable. Take a look at this example:
	
Code/Quote:
<?
if (!isset($_GET["id"])) {
  // No HTTP GET variable
  ?>I'm sorry this page is expecting a HTTP GET variable<?
} else {
  // We got a HTTP GET variable
  ?>Thanks, I got a HTTP GET variable... now to do something with it<?
}
?>
	
This example shows how embeding PHP start/end tags into code can make the 
code much more readable. The other option is to replace the tags and HTML with 
echo's.. See below:
	
Code/Quote:
<?
if (!isset($_GET["id"])) {
  // No HTTP GET variable
  echo "I'm sorry this page is expecting a HTTP GET variable";
} else {
  // We got a HTTP GET variable
  echo "Thanks, I got a HTTP GET variable... now to do something with it";
}
?>
	
Now for this small example you'll have to be the judge what you like better.. 
But perhaps you had to include a large chunk of HTML code.. Are you going to 
wrap all of it in an "echo" construct? You better not! If you wrap a large chunk 
of HTML with "echo" you will have to be careful as you will have to escape 
whatever character you used to open and close the "echo".. See the example below:
	
Code/Quote:
<?
// Lets output a large chunk of HTML.. specifically using form's
echo "<form action=\"process.php\">
      <input type=\"text\" name=\"username\">
      </form>";
?>
	
Now that's an example of terrible implementation, as you had to escape any "'s 
(quotes) .. It would have been much easier to just turn php off (?>) .. put in the 
HTML all nicely formatted, not having to worry about anything, and then turn php 
back on (<?) ..
The last thing I'm going to mention is the use of <?= (short form for echo) .. 
I love using this.. It can make code and scripts very readable. Take a look at the 
2 options below.
	
Code/Quote:
<?
$SQL = "select col1, col2, col3 from table limit 10";
$RES = mysql_query($SQL);
if (mysql_num_rows($RES) == 0) {
  // No rows in the resultset
  echo "Sorry no data";
} else {
  // We have data, display here
  ?>
  <table width="80%" border="0" cellpadding="1" cellspacing="1">
  <tr>
    <td>Value 1</td>
    <td>Value 2</td>
    <td>Value 3</td>
  </tr>
  <?
  while ($R = mysql_fetch_object($RES)) {
    ?>
    <tr>
      <td><?= $R->col1 ?></td>
      <td><?= $R->col2 ?></td>
      <td><?= $R->col3 ?></td>
    </tr>
    <?
  }
  ?>
  </table>
  <?
}
?>
	
I find that format very readable, where you have plain HTML in many instances, 
so if you want to edit the layout, such as add an additional data column, it's 
quite easy, you add 2 lines to the example and you are done. It's very easy to 
find out where you need to add the code as you can see the layout for the table 
header in plain HTML, you know it's 3 columns, and in the loop near the bottom, 
you can clearly see the 3 columns in HTML being output.
That's about it for this quick article.. Please let me know what you'd like to see 
more articles about.. If you have any questions/comments, please post them in 
the "Article Discussion" forum..
ttyl.
	
 
Managed With Tymbrel