ruQueue Programming Style

Overview

Most of ruQueue was coded with a particular coding style. If you would like to contribute to ruQueue please familiarize yourself with this style.

File Header Comments

Each file (HTML, PHP, etc.) should have a comment header that is similar to the following:

//
// Filename:               table.php
// Description:            General software database table functions
// Supprted Language(s):   PHP 5.0+
//

Basically give the name of the file, a description of what sort of code the file contains, and whatever language(s) are supported. For instance, my PHP libraries have been converted to work with PHP 5 or later, so people know that this file won't work if you're running PHP 4 or 3.

Function Header Comments

Each function in a file should have its own comment header that is similar to the following:
//----------------------------------------------------------------------
//
// Function:         Table::__construct
//
// Description:      Class constructor function
//
// Type:             public
//
// Parameters:
//    [in] SWDatabase $db      An open SWDatabase class object
//    [in] string $image_uri   The URI for all images to display
//    [in] array $privs        Associative array of table privileges (see
//                             Remarks)
//    [in] Session $session    Session class object for the active session
//	(in) boolean $is_enabled Is the table enabled?
//                             (Default: true)
//
// Return Values:
//    N/A
//
// Remarks:
//    The keys for the $privs pertain to a particular privilege:
//       'view' = User can view the table
//       'create' = User can create entries in the table
//       'modify' = User can modify existing entries in the table
//       'remove' = User can remove existing records in the table
//       'purge' = User can purge records marked for removal (tombstoned
//                 records)
//    The value of each key should correspond to the actual permission
//    for that table.  The key does not need to exist if the permission
//    is not applicable to the table.
//
//----------------------------------------------------------------------

If the function is part of a class, the function name should indicate Class::Function.

Description gives a short 1-3 line description of the function.

Type describes whether the function might be "static", what its scope is (such as public, private, etc.), etc. In PHP, it's basically everything before the "function" keyword when the function is declared.

Parameters indicates the parameters the function takes. in and out describe whether the parameter is an input parameter or an output parameter. Some parameters may be in/out, which means that it's both. If a parameter is required, surround in, out, in/out with [ ]. If it's optional, surround it with () and then add a line in the parameter description that says (Default: "value"). Surround default string values with " marks.

An "in" parameter means that the parameter is just for input. While the function may change the value, changes won't be saved after the function completes. An "out" parameter means that the caller will pass a variable to the function, but the function will initialize and allocate space for the parameter. Any changes made are returned when the function completes. An "in/out" parameter means that the caller will pass a variable that's initialized, and the function will change that value. Any changes made are returned when the function completes.

Return Values indicates what type of value, error codes, etc. the function will return to the caller. They should be fairly explanatory, but if a lot of explanation is needed, make a note in "Remarks".

Remarks are for longer descriptions of variables, special notes about the function, etc. Basically notate anything special about the function that someone should know when the call it.

Variable Names

All lowercase with words separated by an underscore: $last_name

Constants

All uppercase with underscores: $THIS_IS_MY_CONSTANT

Function Names

Camel-case starting with an uppercase letter: GetUserName()

Class Names

Camel-case: MyClass

Database Table Names

Lowercase with underscores: group_account

Database Field Names

Lowercase with underscores: user_id

Spacing and Indentation

For block indentations, use 2 spaces. If tabs are used, make sure they are converted to spaces before the file is saved. I don't like to use "hard tabs" because some editors treat tabs as different numbers of spaces. It makes code unreadable when you move from editor to editor.

PHP mode in Emacs can make indentation easier.

Don't go past column 79 on a line if you can help it. This makes it so much more readable when you print out code. Sometimes, though, you can't wrap a line at 79 characters, so exceptions to the rule can be made.

Use spaces in a standard way. I.e do this:

 $foo = bar($x, $y);
and not:
 $foo=bar($x,$y) ;

The second of the above is too cramped and the semi-colon shouldn't be so far away.

Forms

Web-based application developers build a lot of HTML forms. Becuase this type of work is tedious ruQueue uses a library.

  1. The library itself: forms.php.txt
  2. An example of the library: generic_form.php
  3. The source of the example of the library: generic_form.php.txt

Note: the above references are here to help you become familiar with the library, but the library above might be out of date. If you are going to use the library please be sure to check the lastest out of CVS.

Note that if you view the source of the generated HTML that it is readable. If you generate your own forms please use the new line character ("\n") to make your machine generated HTML readable.

Auto-forms

Even with the forms.php library it can still be tedious to generate forms. There is a library that uses the forms library above from a higher level of abstraction. It does a 'describe' on a table and based on what it finds it generates PHP code that calls functions from forms.php. It uses some heuristics to make the jump from a table description to what form should be generated.

You can then simply eval the generated code and you will have an XHTML form. This library can save a lot of time. If someone wants a new field we simply alter the table. No messing around with HTML.

Sometimes for large forms what the AutoForm might produce is too rigid looking and the options available to tweak the AutoForm will not be enough. If that is the case you simply print the generated code and paste it into your editor to use it as a building block for your own form. Just remember to include forms.php. Most of the tedious work should be done for you.

  1. The library itself: auto_forms.php.txt
  2. An example of the library: eg_autoform.php.1
  3. The source of the example of the library: eg_autoform.php.txt

Note: the above references are here to help you become familiar with the library, but the library above might be out of date. If you are going to use the library please be sure to check the lastest out of CVS.

Relationship between Database Field Names and Variable Names

Variable names should map one-to-one to our table field names. This will save time for query building via forms. E.g. you can just do the following to build a query:

$sql = "INSERT INTO table_name SET ";
foreach ($_POST as $key => $value) {
  $sql .= "$key='" . CleanUserInput($value) . "', ";  
}
$sql = substr($sql, 0, -2);  // trim last ", "

Instead of the tedium of having some arbitrary mapping between variable names and field names:

$sql = "INSERT INTO table_name SET ";
$sql .= "aVar1='" . $_POST['a_var1'] ."', ";
$sql .= "aVar2='" . $_POST['a_var2'] ."', ";
...
$sql .= "aVarN='" . $_POST['a_varN'] ."', ";

where how many lines above you have to have is how many field names there will be in your query.

Variable Name Choice

Use nice sounding and meaningfull field/variable names. Try not to use one letter variables names unless you are doing a simple loop.

The autoform (see Auto-forms) can make life easier. I'll quickly explain how it might work:

  1. 'describe table_foo;' yields a varchar field named first_name.
  2. it generates an HTML form with:
  3.  <strong>First Name</strong>
     <input type="text" name="first_name" />
    

Note that it sets the form up so that the variable $_POST['first_name'] (or $_GET, it decides based on an argument) follows the rule about keeping variable names and field names the same.

Note also that it got "First Name" by doing:

 ucwords(str_replace('_', '', $var))

The autoform can only make your life easier if you use var names that will translate nicely to something the user can follow. You should pick your varialbe names to be meaningfull for the people reading your code, but you should also try (within reason) to make them "user-friendly" if the above two functions are called on them.

We've established that we want our variable names to lower case with underscores. Here is *one* exception in the case of acronyms and the autoform: if your variable names are acronymic use uppercase letters for the acronym. E.g. ID is short for "Identification Number", so you would use employee_ID since:

 ucwords(str_replace('_', '', 'employee_ID'))

yields "Employee ID".

PHP Tags

Use the full '<?php ?>' tags to enclose your code, not the older abbreviated '<? ?>' tags.

Vim Mode for these Standards

You can use this .vimrc file with Vim so that your F2 and F3 keys will fill in the file and function templates described in this document.

Emacs Mode for these Standards

If you use Emacs there are some commands that you can add to your environment to make it easier for you to follow these standards. To use these commands:

  1. Put this file in your .emacs
  2. Use the new "commands" that the mode provides.

Using the new commands is easy. For example, if you want a header as described above type:

M-x code-header

The first part of the above would be read as Meta x. If your alt key does not translate to Meta (i.e. you should see a M-x in the minibuffer when you hold down alt and type "x") then you can use the escape key. To do this, simply type the escape key, release it and then type "x". This will produce the exact same effect as typing M-x.

Strictly speaking this is not a new Emacs mode. It is just a collection of new commands to extend your environment to make it easier to follow the standards.

These new emacs commands also make it easier for you to do common tasks in PHP. You can probably relate to the following:

"If I had a nickel for every time I've written "for (i = 0; i < N; i++)" in C I'd be a millionaire." - Mike Vanier

If you have added the above file to your .emacs you can simply type:

M-x php-for-loop

(note that typing the above is easy since emacs has tab completion and have the result be:

for ($i = 0; $i < $j; $i++) {
  
}

This might save you some time. There is a small collection of common PHP lines in the above file. Just type:

M-x php

and type tab twice to see what short cuts are built in (type Control g to quit).

[TOP]


For questions or comments about this site, contact webmaster@nbcs.rutgers.edu

Last Updated: May 14, 2006 10:51 AM

© 2009 Rutgers, The State University of New Jersey. All rights reserved.

Search Rutgers