At Turboweb, we care about our code – we care about it so much that we wanted to make sure that we all code properly, and to that end we’ve all agreed on the document below. It’s a living document, so we sometimes make changes here and there. If you have any comments to make please go ahead.
Things that may need to be worked into this document:
- register globals OFF
- magic quotes OFF
- $HTTP_POST_VARS vs. $_POST (etc)
- sanitising input – cast vs. check, exceptions vs. continuation
- where to (and where not to) use addslashes/stripslashes
- code indentation
- output inside functions
- mixing code and html (i.e. templating)
- accessing the database
- deleting records – using LIMIT clauses
- handling errors
- sending email
- write errors to file on production server
- check that array is populated before doing things with it
Note: The Turboweb Coding Standards are based on the Drupal Coding Standards which in turn is loosely based on the PEAR Coding standards. Comments and names should use US English spelling (“color” not “colour” etc.).
Contents of this Page
- Sample Content / Images
- Indenting and Whitespace
- Operators
- Control Structures
- Function Calls
- Function Declarations
- Arrays
- Quotes
- String Concatenations
- Comments
- Including Code
- PHP Code Tags
- Semicolons
- Subversion Header
- Example URLs
- Naming Conventions (Functions, Constants, Global Variables, Classes, Files)
- CSS Code (Suggested style guide for comment)
Sample Content / Images
You must at all times consider any development or staging platform that you are working on to be a client facing system, and therefore any sample content or images used should reflect the level of professionalism that Turboweb puts forth.
Sample Content
Where sample content is required, “lorem ipsum” text is entirely appropriate. This can be easily sourced from http://www.lipsum.com/. Where possible, ensure that the content is clearly marked as “test” content.
Sample Images
Internally we will have a pool of sample images to provide clients with visual examples. In addition to these, any images supplied by the client for the job being undertaken are also appropriate.
Inappropriate Content
Any content that is likely to offend or confuse a client is considered inappropriate. In general, use your common sense. Cat pictures and people falling on their heads while amusing are not appropriate.
Indenting and Whitespace
- Use an indent of one tab, not spaces. It is recommended to set your editor to have a tab width of 4 spaces. A tab character should only ever be used to indent code and should not appear elsewhere in a file. This allows us to easily adjust the indent method to suit other coding standards in the future if need be.
- Lines should have no trailing whitespace at the end.
- Files should be formatted with \n as the line ending (Unix line endings), not \r\n (Windows line endings).
Operators
- All binary operators (operators that come between two values), such as +, -, =, !=, ==, >, etc. should have a space before and after the operator, for readability. For example, an assignment should be formatted as $foo = $bar; rather than $foo=$bar;.
- Unary operators (operators that operate on only one value), such as ++, should not have a space between the operator and the variable or number they are operating on.
Control Structures
Control structures include if, for, while, switch, etc. Here is a sample if statement, since it is the most complicated of them:
if (condition1 || condition2) { action1; } elseif (condition3 && condition4) { action2; } else { defaultaction; }
Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls.
You are strongly encouraged to always use curly braces even in situations where they are technically optional. Having them increases readability and decreases the likelihood of logic errors being introduced when new lines are added.
For switch statements:
switch (condition) { case 1: action1; break; case 2: action2; break; default: defaultaction; }
Function Calls
Functions should be called with no spaces between the function name and the opening parenthesis; spaces between the opening parenthesis and the first parameter, spaces between commas and each parameter, and a space between the last parameter and the closing parenthesis, and finally no space between the closing parenthesis and the semicolon. Here’s an example:
$var = foo( $bar, $baz, $quux );</p>
As displayed above, there should be one space on either side of an equals sign used to assign the return value of a function to a variable. In the case of a block of related assignments, more space may be inserted to promote readability:
$short = foo($bar); $long_variable = foo($baz);
Function Declarations
function myFunkyFunction($foo) { $foo = $foo + 5; return $foo; }
Arguments with default values go at the end of the argument list. Always attempt to return a meaningful value from a function if one is appropriate.
Arrays
Arrays should be formatted with a space separating each element (after the comma), and spaces around the => key association operator, if applicable:
$some_array = array(‘hello’, ‘world’, ‘foo’ => ‘bar’);
Note that if the line declaring an array spans longer than 80 characters (often the case with form and menu declarations), each element should be broken into its own line, and indented one level:
$account = array( 'name' => 'Joe Public', 'email' => 'joe@public.com', 'phone' => '555-5555', 'address' => '123 Main Street, Mainsville, Maine', 'accountNumber' => '12345678' );
To aid readability, the following alternative of the above is also acceptable:
$account = array( 'name' => 'Joe Public', 'email' => 'joe@public.com', 'phone' => '555-5555', 'address' => '123 Main Street, Mainsville, Maine', 'accountNumber' => '12345678' );
Note: Use tabs in this situation, not spaces.
Quotes
The mixing of single and double quotes is left to the discretion of the developer to use appropriately (e.g. to avoid excessive escaping). Where possible the use of single quotes is preferred over double quotes. This is because single quote strings are known to be faster because the parser doesn't have to look for in-line variables. Their use is recommended except in two cases:
- In-line variable usage, e.g. "<h2>$header</h2>".
- Translated strings where one can avoid escaping single quotes by enclosing the string in double quotes. One such string would be "He's a good person." It would be 'He\'s a good person.' with single quotes. Such escaping may not be handled properly by .pot file generators for text translation, and it's also somewhat awkward to read.
String Concatenations
Always use a space between the dot and the concatenated parts to improve readability.
<?php $string = 'Foo' . $bar; $string = $bar . 'foo'; $string = bar() . 'foo'; $string = 'foo' . 'bar'; ?>
When you concatenate simple variables, you can use double quotes and add the variable inside; otherwise, use single quotes.
<?php $string = "Foo $bar"; ?>
When using the concatenating assignment operator ('.='), use a space on each side as with the assignment operator:
<?php $string .= 'Foo'; $string .= $bar; $string .= baz(); ?>
Comments
Inline documentation for source files should follow the Doxygen formatting conventions.
Non-documentation comments are strongly encouraged. A general rule of thumb is that if you look at a section of code and think "Wow, I don't want to try and describe that", you need to comment it before you forget how it works.
Non-documentation comments should use capitalized sentences with punctuation. Sentences should be separated by single spaces. All caps are used in comments only when referencing constants, for example TRUE. Comments should be on a separate line immediately before the code line or block they reference. For example:
// Unselect all other contact categories. db_query('UPDATE {contact} SET selected = 0');
If each line of a list needs a separate comment, the comments may be given on the same line and may be formatted to a uniform indent for readability.
C style comments (/* */) and standard C++ comments (//) are both fine. Use of Perl/shell style comments (#) is discouraged.
Including Code
Anywhere you are unconditionally including a class file, use require_once(). Anywhere you are conditionally including a class file (for example, factory methods), use include_once(). Either of these will ensure that class files are included only once. They share the same file list, so you don't need to worry about mixing them - a file included with require_once() will not be included again by include_once().
Note: include_once() and require_once() are statements, not functions. You don't need parentheses around the file name to be included.
When including code from the same directory or a sub-directory, start the file path with ".":
include_once './includes/mymodule_formatting.inc';
It is good practiced to define a variable that holds the base directory:
require_once APPLICATION_ROOT . '/' . variable_get('cache_inc', 'includes/cache.inc');
PHP Code Tags
Always use <?php ?> to delimit PHP code, not the shorthand, <? ?>. This is the most portable way to include PHP code on differing operating systems and set-ups.
It is recommended that the ?> at the end of code files is purposely omitted. The reasons for this can be summarized as:
- Removing it eliminates the possibility for unwanted whitespace at the end of files which can cause "header already sent" errors, XHTML/XML validation issues, and other problems.
- The closing delimiter at the end of a file is optional.
- PHP.net itself removes the closing delimiter from the end of its files (example: prepend.inc), so this can be seen as a "best practice."
Semicolons
The PHP language requires semicolons at the end of most lines, but allows them to be omitted at the end of code blocks. Even though these are optional we require them to be present, even at the end of code blocks. In particular, for one-line PHP blocks:
<?php print $tax; ?> -- YES <?php print $tax ?> -- NO
Example URLs
Use "example.com" for all example URLs, per RFC 2606.
Naming Conventions
Functions
Functions should be named using "lowerCamelCase". As a good developer you will be aware of the inherent danger of defining functions in the global namespace and will do your best to use a naming convention that is unlikely to cause collisions. If in doubt, use a class instead.
Constants
Constants should always be all-uppercase, with underscores to separate words. The pre-defined PHP constants like true, false and null should be spelt in lower case.
Global Variables
Even though you think you do, you probably don't need to define a global variable (consider other options first, such as class member variables). They should be defined as "lowerCamelCase".
Classes
- Classes should be named using "CamelCase."
Example:
abstract class DatabaseConnection extends PDO
{
...
}
As a good developer you will be aware of the inherent danger of naming classes with generic names as they are registered in the global namespace. If in doubt, use a prefix so that you class is called TurbowebUpload for example instead of Upload. The namespace feature of PHP5.3 will help in this respect but it's adoption is not yet widespread.
Methods
- All methods should be denoted public, private or protected.
- Some people distinguish between public and private methods by use of CamelCase. We don't. All methods should be "lowerCamelCase":
Example:
class BobsClassOfGreatness { public function renderTable() { return $this->loadRecord(); } private function loadRecord() { ... } }
The use of private class methods and properties should be avoided -- use protected instead, so that another class could extend your class and change the method if necessary. Protected (and public) methods and properties should not use an underscore prefix, as was common in PHP 4-era code.
Member Variables
- should be declared at the top of a class definition
- should be denoted public, private or protected
- should be "lowerCamelCase"
- default values may be specified at time of declaration
Example:
class BobsClassOfMemberVariables { private $indexNumber = 0; public $firstName; }
Class Constants
- as with member variables should be declared at the top of a class definition
- should be "UPPERCASE_WITH_UNDERSCORES_FOR_SPACES"
- should be referred to within the class with the self:: operator
Example:
class BobsClassOfConstants { const TEXT_UPPERCASE = 1; const TEXT_LOWERCASE = 2; public function DoSomething( $inputString, $operation ) { if ( $operation == self::TEXT_UPPERCASE ) { return strtoupper( $inputString ); } if ( $operation == self::TEXT_LOWERCASE ) { return strtolower( $inputString ); } } }
File names
All documentation files should have the file name extension ".txt" to make viewing them on Windows systems easier. Also, the file names for such files should be all-caps (e.g. README.txt instead of readme.txt) while the extension itself is all-lowercase (i.e. txt instead of TXT).
Examples: README.txt, INSTALL.txt, TODO.txt, CHANGELOG.txt etc.
CSS Code (Suggested style guide for comment)
CSS code should be different in some key ways. The intention is to make CSS look different from other code to make it recognisible.
The key differences are in naming of ID's or Classes. They should be all lowercase with hyphens to separate words.. eg ".my-class-name" not ".My_Class_Name". Also the placement and indentation of braces are different. The first brace should be placed at the end of the same line as the ID or Class declaration. E.g. ".my-class-name {". also the last brace should not be indented and on a separate line.
Each declaration shoul be on a separate line with one tab indentation. Do not run multiple declarations on one line.
Always place a semi-colon at the end of each declaration line. The reason is that it is too easy to come along later to add another line at the end of the block and not have it work as expected because there is a missing semi-colon.
If you are declaring multiple values for a similar thing such as padding try and set them in one line. For example instead of:
.my-test-class { padding-left: 10px; padding-right: 8px; padding-top: 5px; padding-bottom: 2px; }
Use:
.my-test-class { padding: 5px 8px 2px 10px; }
Here is an example of good CSS code.
.my-test-class { border: 1px solid #000000; background: #ff9900; color: #ffffff; }
CSS Code (Bob's suggestions for comment)
CSS Comments
The only valid CSS comment is the C-style block quote. Use it to describe where particular styles are used in your application.
Example:
/* Format for login box */ .loginBox { .... }
Naming of Classes and ID's
Classes and ID's should be named in lowerCamelCaps. The reason for this is to be consistent with the programming style guide and to avoid confusion about whether it should be login_box, login-box, loginbox etc. This also means that if any frameworks are being used where the ID's of the elements are automatially bound to the application in some way then there won't be any need to alter stylesheets to suit.
Remember: ID's can only appear once in a document, classes can appear multiple times.
Example:
.loginBox { .... }
CSS Colors
You may decide to use CSS colour names, in which case a list of colours supported by major browsers can be found here: http://www.w3schools.com/css/css_colornames.asp. To avoid disappointment (and rework!) it is suggested that you use these colour names for situations where it is very obvoius what is intended for example black, red, white, blue, green etc. Try to avoid using colours like CornflowerBlue, LightGoldenRodYellow and PapayaWhip where equivalent #rgb notations are available.
The three digit hex shorthand abbreviations (#rgb) of the full notation (#rrggbb) are discouraged, simply because they were introduced in the CSS3 spec and as such there may be browsers that do not support this notation. When using this scheme, #123 is eqivalent to #112233.
Separation of Layout and Design
Declarations detailing layout should be kept separate from declarations detailing design. This provides for separation of form and content, allowing the CSS developer to fine tune the layout of a design while staying away from the design. It is left up to the project team who are working on a particular project but there are merits for using separate CSS files for layout and design. Silverstripe and Twitter are two applications that do this well.
Example:
/* Design section of CSS */ .loginBox { background-color: yellow; color: red; border-color: blue; } /* Layout section of CSS */ .loginBox { border-width: 2px; border-style: solid; padding: 10px; margin: 20px; } /* Combined style - listed for illustration purposes */ .loginBox { background-color: yellow; color: red; border-color: blue; border-width: 2px; border-style: solid; padding: 10px; margin: 20px; }
Note: The use of this technique may affect your ability to use CSS shorthand (see below).
Line Formatting
When declaring CSS, the selector should go on a line by itself, followed by a open parenthesis on the following line at the same level of indentation as the selector, followed by each CSS property, indented by one tab character and then finally terminated by a closing parenthesis on a line by itself at the same indent level as the selector.
Where appropriate you may specify two or more selectors in which case each selector should be separated by a comma and a new line character. Indentation of each successive selector should be the same as the initial one.
Examples:
.lightBlue { color: #d0d0ff; } #errorText, #logoutButton, #pageFooter { color: red; background-color: yellow; border: 2px black solid; padding: 10px; margin: 10px; }
CSS Shorthand
It is left to the user to apply judgement over where CSS shorthand should be used. In general the rule of thumb is that if it makes it easier to read then you should use CSS shorthand, however if it serves to complicate the CSS then you are better off to explicitly declare each element.
Examples:
#loginBox { border: 1px black solid; }
Note: If you choose to use CSS shorthand the browser will explicitly define defaults for those properties that you do not specify. The following guide appears to be a good reference point for this: http://www.dustindiaz.com/css-shorthand/

