This is the April, 2005 revision of the phpBB Coding Guidelines, all attempts should be made to follow it as closely as possible. This document is (c) 2005 phpBB Group, copying or redistribution is not allowed without permission.

Coding Guidelines


1. Defaults

1.i. Editor Settings

Tabs vs Spaces:

In order to make this as simple as possible, we will be using tabs, not spaces. Feel free to set how many spaces your editor uses when it displays tabs, but make sure that when you save the file, it's saving tabs and not spaces. This way, we can each have the code be displayed the way we like it, without breaking the layout of the actual files.

Linefeeds:

Ensure that your editor is saving files in the UNIX format. This means lines are terminated with a newline, not with a CR/LF combo as they are on Win32, or whatever the Mac uses. Any decent editor should be able to do this, but it might not always be the default. Know your editor. If you want advice on Windows text editors, just ask one of the developers. Some of them do their editing on Win32.

Top

1.ii. File Header

Standard header for new files:

This template of the header must be included at the start of all phpBB files:

/** 
*
* @package {PACKAGENAME}
* @version $Id: $
* @copyright (c) 2005 phpBB Group 
* @license http://opensource.org/licenses/gpl-license.php GNU Public License 
*
*/
	

Please see the File Locations section for the correct package name.

Files containing inline code:

For those files you have to put an empty comment directly after the header to prevent the documentor assigning the header to the first code element found.

/**
*
* {HEADER}
*
*/

/**
*/
{CODE}
	

Files containing only functions:

Do not forget to comment the functions (especially the first function following the header). Each function should have at least a comment of what this function does. For more complex functions it is recommended to document the parameters too.

Files containing only classes:

Do not forget to comment the class. Classes need a seperate @package definition, it is the same as the header package name. Apart from this special case the above statement for files containing only functions needs to be applied to classes and it's methods too.

Code following the header but only functions/classes file:

If this case is true, the best method to avoid documentation confusions is adding an ignore command, for example:

/** 
*
* {HEADER}
*
*/

/**
* @ignore
*/
Small code snipped, mostly one or two defines or an if statement

/**
* {DOCUMENTATION}
*/
class ...
	
Top

1.iii. File Locations

Functions used by more than one page should be placed in functions.php, functions specific to one page should be placed on that page (at the bottom) or within the relevant sections functions file.

The following packages are defined, and related new features/functions should be placed within the mentioned files/locations, as well as specifying the correct package name. The package names are bold within this list:

Top


2. Code Layout/Guidelines

2.i. Variable/Function Naming

We will not be using any form of hungarian notation in our naming conventions. Many of us believe that hungarian naming is one of the primary code obfuscation techniques currently in use.

Variable Names:

Variable names should be in all lowercase, with words separated by an underscore, example:

$current_user is right, but $currentuser and $currentUser are not.

Names should be descriptive, but concise. We don't want huge sentences as our variable names, but typing an extra couple of characters is always better than wondering what exactly a certain variable is for.

Loop Indices:

The only situation where a one-character variable name is allowed is when it's the index for some looping construct. In this case, the index of the outer loop should always be $i. If there's a loop inside that loop, its index should be $j, followed by $k, and so on. If the loop is being indexed by some already-existing variable with a meaningful name, this guideline does not apply, example:

for ($i = 0; $i < $outer_size; $i++)
{
   for ($j = 0; $j < $inner_size; $j++)
   {
      foo($i, $j);
   }
}
	

Function Names:

Functions should also be named descriptively. We're not programming in C here, we don't want to write functions called things like "stristr()". Again, all lower-case names with words separated by a single underscore character. Function names should preferably have a verb in them somewhere. Good function names are print_login_status(), get_user_data(), etc.

Function Arguments:

Arguments are subject to the same guidelines as variable names. We don't want a bunch of functions like: do_stuff($a, $b, $c). In most cases, we'd like to be able to tell how to use a function by just looking at its declaration.

Summary:

The basic philosophy here is to not hurt code clarity for the sake of laziness. This has to be balanced by a little bit of common sense, though; print_login_status_for_a_given_user() goes too far, for example -- that function would be better named print_user_login_status(), or just print_login_status().

Special Namings:

For all emoticons use the term smiley in singular and smilies in plural.

Top

2.ii. Code Layout

Always include the braces:

This is another case of being too lazy to type 2 extra characters causing problems with code clarity. Even if the body of some construct is only one line long, do not drop the braces. Just don't, examples:

// These are all wrong.

if (condition) do_stuff();

if (condition)
	do_stuff();

while (condition)
	do_stuff();

for ($i = 0; $i < size; $i++)
	do_stuff($i);
	

// These are all right.

if (condition)
{
	do_stuff();
}

while (condition) 
{
	do_stuff();
}

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

Where to put the braces:

This one is a bit of a holy war, but we're going to use a style that can be summed up in one sentence: Braces always go on their own line. The closing brace should also always be at the same column as the corresponding opening brace, examples:

if (condition) 
{
	while (condition2)
	{
		...
	}
}
else 
{
	...
}

for ($i = 0; $i < $size; $i++) 
{
	...
}
		
while (condition) 
{
	...
}
		
function do_stuff() 
{
	...
}
	

Use spaces between tokens:

This is another simple, easy step that helps keep code readable without much effort. Whenever you write an assignment, expression, etc.. Always leave one space between the tokens. Basically, write code as if it was English. Put spaces between variable names and operators. Don't put spaces just after an opening bracket or before a closing bracket. Don't put spaces just before a comma or a semicolon. This is best shown with a few examples, examples:

// Each pair shows the wrong way followed by the right way.

$i=0;
$i = 0;
		
if($i<7) ...
if ($i < 7) ...
		
if ( ($i < 7)&&($j > 8) ) ...
if ($i < 7 && $j > 8) ...
		
do_stuff( $i, "foo", $b );
do_stuff($i, "foo", $b);
		
for($i=0; $i<$size; $i++) ...
for($i = 0; $i < $size; $i++) ... 
		
$i=($j < $size)?0:1;
$i = ($j < $size) ? 0 : 1;
	

Operator precedence:

Do you know the exact precedence of all the operators in PHP? Neither do I. Don't guess. Always make it obvious by using brackets to force the precedence of an equation so you know what it does. Remember to not over-use this, as it may harden the readability. Basically, do not enclose single expressions. Examples:

// what's the result? who knows.

$bool = ($i < 7 && $j > 8 || $k == 4);
	

// now you can be certain what I'm doing here.

$bool = (($i < 7) && (($j < 8) || ($k == 4)))
	

// But this one is even better, because it is easier on the eye but the intention is preserved

$bool = ($i < 7 && ($j < 8 || $k == 4))
	

Quoting strings:

There are two different ways to quote strings in PHP - either with single quotes or with double quotes. The main difference is that the parser does variable interpolation in double-quoted strings, but not in single quoted strings. Because of this, you should always use single quotes unless you specifically need variable interpolation to be done on that string. This way, we can save the parser the trouble of parsing a bunch of strings where no interpolation needs to be done.

Also, if you are using a string variable as part of a function call, you do not need to enclose that variable in quotes. Again, this will just make unnecessary work for the parser. Note, however, that nearly all of the escape sequences that exist for double-quoted strings will not work with single-quoted strings. Be careful, and feel free to break this guideline if it's making your code easier to read, examples:

// wrong

$str = "This is a really long string with no variables for the parser to find.";

do_stuff("$str");
	

// right

$str = 'This is a really long string with no variables for the parser to find.';

do_stuff($str);
	

// Sometimes single quotes are just not right

$post_url = $phpbb_root_path . 'posting.' . $phpEx . '?mode=' . $mode . '&amp;start=' . $start;
	

// Double quotes are sometimes needed to not overcroud the line with concentinations

$post_url = "{$phpbb_root_path}posting.$phpEx?mode=$mode&amp;start=$start";
	

In SQL Statements mixing single and double quotes is partly allowed (following the guidelines listed here about SQL Formatting), else it should be tryed to only use one method - mostly single quotes.

Associative array keys:

In PHP, it's legal to use a literal string as a key to an associative array without quoting that string. We don't want to do this -- the string should always be quoted to avoid confusion. Note that this is only when we're using a literal, not when we're using a variable, examples:

// wrong

$foo = $assoc_array[blah];
	

// right

$foo = $assoc_array['blah'];
	

Comments:

Each complex function should be preceded by a comment that tells a programmer everything they need to know to use that function. The meaning of every parameter, the expected input, and the output are required as a minimal comment. The function's behaviour in error conditions (and what those error conditions are) should also be present.

Especially important to document are any assumptions the code makes, or preconditions for its proper operation. Any one of the developers should be able to look at any part of the application and figure out what's going on in a reasonable amount of time. Avoid using /* */ comment blocks for one-line comments, // should be used for one/two-liners.

Magic numbers:

Don't use them. Use named constants for any literal value other than obvious special cases. Basically, it's ok to check if an array has 0 elements by using the literal 0. It's not ok to assign some special meaning to a number and then use it everywhere as a literal. This hurts readability AND maintainability. The constants true and false should be used in place of the literals 1 and 0 -- even though they have the same values (but not type!), it's more obvious what the actual logic is when you use the named constants. Typecast variables where it is needed, do not rely on the correct variable type (PHP is currently very loose on typecasting which can lead to security problems if a developer does not have a very close eye to it).

Shortcut operators:

The only shortcut operators that cause readability problems are the shortcut increment $i++ and decrement $j-- operators. These operators should not be used as part of an expression. They can, however, be used on their own line. Using them in expressions is just not worth the headaches when debugging, examples:

// wrong

$array[++$i] = $j;
$array[$i++] = $k;
	

// right

$i++;
$array[$i] = $j;

$array[$i] = $k;
$i++;
	

Inline conditionals:

Inline conditionals should only be used to do very simple things. Preferably, they will only be used to do assignments, and not for function calls or anything complex at all. They can be harmful to readability if used incorrectly, so don't fall in love with saving typing by using them, examples:

// Bad place to use them

($i < $size && $j > $size) ? do_stuff($foo) : do_stuff($bar);
	

// OK place to use them

$min = ($i < $j) ? $i : $j;
	

Don't use uninitialized variables.

For phpBB3, we intend to use a higher level of run-time error reporting. This will mean that the use of an uninitialized variable will be reported as a warning. These warnings can be avoided by using the built-in isset() function to check whether a variable has been set, examples:

// Wrong

if ($forum) ...
	

// Right

if (isset($forum)) ...
	

// Also possible

if (isset($forum) && $forum == 5)
	
Top

2.iii. SQL/SQL Layout

Common SQL Guidelines:

All SQL should be cross-DB compatible, if DB specific SQL is used alternatives must be provided which work on all supported DB's (MySQL3/4/5, MSSQL (7.0 and 2000), PostgreSQL (7.0+), Firebird, SQLite, Oracle8, ODBC (generalised if possible, otherwise DB2)).

All SQL commands should utilise the DataBase Abstraction Layer (DBAL)

SQL code layout:

SQL Statements are often unreadable without some formatting, since they tend to be big at times. Though the formatting of sql statements adds a lot to the readability of code. SQL statements should be formatted in the following way, basically writing keywords :

$sql = 'SELECT * 
<-one tab->FROM ' . SOME_TABLE . ' 
<-one tab->WHERE a = 1 
<-two tabs->AND (b = 2 
<-three tabs->OR b = 3) 
<-one tab->ORDER BY b';
	

Here the example with the tabs applied:

$sql = 'SELECT * 
	FROM ' . SOME_TABLE . ' 
	WHERE a = 1 
		AND (b = 2 
			OR b = 3) 
	ORDER BY b';
	

SQL Quotes:

Double quotes where applicable ... examples:

// These are wrong.

"UPDATE " . SOME_TABLE . " SET something = something_else WHERE a = $b"; 

'UPDATE ' . SOME_TABLE . ' SET something = ' . $user_id . ' WHERE a = ' . $something; 
	

// These are right.

'UPDATE ' . SOME_TABLE . " SET something = something_else WHERE a = $b"; 

'UPDATE ' . SOME_TABLE . " SET something = $user_id WHERE a = $something"; 
	

In other words use single quotes where no variable substitution is required or where the variable involved shouldn't appear within double quotes. Otherwise use double quotes.

Common DBAL methods:

Always use $db->sql_escape() if you need to check for a string within an SQL statement, for example:

$sql = 'SELECT *
	FROM ' . SOME_TABLE . "
	WHERE username = '" . $db->sql_escape($username) . "'";
	

If you need to UPDATE or INSERT data, make use of the $db->sql_build_array() function. This function already escapes strings and checkes other types, so there is no need to do this here. The data to be inserted should go into an array - $sql_ary - or directly within the statement if one one or two variables needs to be inserted/updated. An example of an insert statement would be:

$sql_ary = array(
	'somedata'		=> $my_string,
	'otherdata'		=> $an_int,
	'moredata'		=> $another_int
);

$db->sql_query('INSERT INTO ' . SOME_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
	

To complete the example, this is how an update statement would look like:

$sql_ary = array(
	'somedata'		=> $my_string,
	'otherdata'		=> $an_int,
	'moredata'		=> $another_int
);

$sql = 'UPDATE ' . SOME_TABLE . ' 
	SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
	WHERE user_id = $user_id";
$db->sql_query($sql);
	
Top

2.iv. Optimizations

Operations in loop definition:

Always try to optimize your loops if operations are going on at the comparing part, since this part is executed every time the loop is parsed through. For assignments a descriptive name should be chosen. Example:

// On every iteration the sizeof function is called

for ($i = 0; $i < sizeof($post_data); $i++)
{
	do_something();
}
	

// You are able to assign the (not changing) result within the loop itself

for ($i = 0, $size = sizeof($post_data); $i < $size; $i++)
{
	do_something();
}
	

Use of in_array():

Try to avoid using in_array() on huge arrays, and try to not place them into loops if the array to check consist of more than 20 entries. in_array() can be very time consuming and uses a lot of cpu processing time. For little checks it is not noticable, but if checked against a huge array within a loop those checks alone can be a bunch of seconds.

Top

2.v. General Guidelines

General things:

Never trust user input.

The auth class should be used for all authorisation checking

No attempt should be made to remove any copyright information (either contained within the source or displayed interactively when the source is run/compiled), neither should the copyright information be altered in any way (it may be added to)

Variables:

Make use of the request_var() function for anything except for submit or single checking params. Example:

// Old method, do not use it

$start = (isset($HTTP_GET_VARS['start'])) ? intval($HTTP_GET_VARS['start']) : intval($HTTP_POST_VARS['start']);
$submit = (isset($HTTP_POST_VARS['submit'])) ? true : false;
	

// Use request var and define a default variable (use the correct type)

$start = request_var('start', 0);
$submit = (isset($_POST['submit'])) ? true : false;
	

// $start is an int, the following use of request_var therefore is not allowed

$start = request_var('start', '0');
	

Login checks/redirection:

To show a forum login box use login_forum_box($forum_data), else use the login_box() function.

Sensitive Operatiosn:

For sensitive operations always let the user confirm the action. For the confirmation screens, make use of the confirm_box() function.

Sessions:

Sessions should be initiated on each page, as near the top as possible using the following code:

$user->session_begin();
$auth->acl($user->data);
$user->setup();
	

The $user->setup() call can be used to pass on additional language definitions and a custom style (used in viewforum).

Errors and messages:

All messages/errors should be output by calling trigger_error() using the appropriate message type and language string. Example:

trigger_error('NO_FORUM');
	

General Functions:

Use sizeof instead of count, this is just a general preference and guideline and has no other benefit.

Use strpos instead of strstr.

Top


3. Styling

General things

Templates should be produced in a consistent manner. Where appropriate they should be based off an existing copy, e.g. index, viewforum or viewtopic (the combination of which implement a range of conditional and variable forms).

The outer table class forumline has gone and is replaced with tablebg.

When writing <table> the order <table class="" cellspacing="" cellpadding="" border="" align=""> creates consistency and allows everyone to easily see which table produces which "look". The same applies to most other tags for which additional parameters can be set, consistency is the major aim here.

Each block level element should be indented by one tab, same for tabular elements, e.g. <tr> <td> etc., whereby the intendiation of <table> and the following/ending <tr> should be on the same line. This applies not to div elements of course.

Don't use <span> more than is essential ... the CSS is such that text sizes are dependent on the parent class. So writing <span class="gensmall"><span class="gensmall">TEST</span></span> will result in very very small text. Similarly don't use span at all if another element can contain the class definition, e.g.

<td><span class="gensmall">TEST</span></td>

can just as well become:

<td class="gensmall">TEST</td>

Try to match text class types with existing useage, e.g. don't use the nav class where viewtopic uses gensmall for example.

Row colours/classes are now defined by the template, use an IF S_ROW_COUNT switch, see viewtopic or viewforum for an example.

Remember block level ordering is important ... while not all pages validate as XHTML 1.0 Strict compliant it is something we're trying to work too.

Use a standard cellpadding of 2 and cellspacing of 0 on outer tables. Inner tables can vary from 0 to 3 or even 4 depending on the need.

Use div container for styling and table for data representation

The seperate catXXXX and thXXX classes are gone. When defining a header cell just use <th> rather than <th class="thHead"> etc. Similarly for cat, don't use <td class="catLeft"> use <td class="cat"> etc.

Try to retain consistency of basic layout and class useage, i.e. _EXPLAIN text should generally be placed below the title it explains, e.g. {L_POST_USERNAME}<br /><span class="gensmall">{L_POST_USERNAME_EXPLAIN}</span> is the typical way of handling this ... there may be exceptions and this isn't a hard and fast rule

Try to keep template conditional and other statements tabbed in line with the block to which they refer.

this is incorrect

<!-- BEGIN test -->
	<tr>
		<td>{test.TEXT}</td>
	</tr>
<!-- END test -->

this is correct:

<!-- BEGIN test -->
<tr>
	<td>{test.TEXT}</td>
</tr>
<!-- END test -->

it gives immediate feedback on exactly what is looping.

Top


4. Templating

File naming

Firstly templates now take the suffix ".html" rather than ".tpl". This was done simply to make the lifes of some people easier wrt syntax highlighting, etc.

Variables

All template variables should be named appropriately (using underscores for spaces), language entries should be prefixed with L_, system data with S_, urls with U_, all other variables should be presented 'as is'.

Note that unlike 2.0.x most language strings are not assigned from the source. When a language variable is found {L_YYYYYY} phpBB first looks if an assigned variable exists with that name. If it does, it uses that. If not it looks if an exsting string defined in the language file exists. This should reduce the need to assign loads of new lang vars in Mods.

Blocks

The basic block level loop remains and takes the form:

<!-- BEGIN loopname -->
markup, {loopname.X_YYYYY}, etc.
<!-- END loopname -->

However this has now been extended with the following additions. Firstly you can set the start and end points of the loop. For example:

<!-- BEGIN loopname(2) -->
markup
<!-- END loopname -->

Will start the loop on the third entry (note that indexes start at zero). Extensions of this are:

loopname(2,4): Starts loop on third values, ends on fourth
loopname(-4): Starts loop fourth from last value
loopname(2, -4): Starts loop on third value, ends four from end

Note that the indexing method may change since it's not really consistent at this time :)

A further extension to begin is BEGINELSE:

<!-- BEGIN loop -->
markup
<!-- BEGINELSE -->
markup
<!-- END loop -->

This will cause the markup between BEGINELSE and END to be output if the loop contains no values. This is useful for forums with no topics (for example) ... in some ways it replaces "bits of" the existing "switch_" type control (the rest being replaced by conditionals, see below).

Including files

Something that existed in 2.0.x which no longer exists in 3.0.x is the ability to assign a template to a variable. This was used (for example) to output the jumpbox. Instead (perhaps better, perhaps not but certainly more flexible) we now have INCLUDE. This takes the simple form:

<!-- INCLUDE filename -->

You will note in the 3.0 templates the major sources start with <!-- INCLUDE overall_header.html --> or <!-- INCLUDE simple_header.html -->, etc. In 2.0.x control of "which" header to use was defined entirely within the code. In 3.0.x the template designer can output what they like. Note that you can introduce new templates (i.e. other than those in the default set) using this system and include them as you wish ... perhaps useful for a common "menu" bar or some such. No need to modify loads of files as with 2.0.x.

PHP

A contentious decision has seen the ability to include PHP within the template introduced. This is achieved by enclosing the PHP within relevant tags:

<!-- PHP -->
echo "hello!";
<!-- ENDPHP -->

You may also include PHP from an external file using:

<!-- INCLUDEPHP somefile.php -->

it will be included and executed inline.

A note, it is very much encouraged that template designers do not include PHP. The ability to include raw PHP was introduced primarily to allow end users to include banner code, etc. without modifying multiple files (as with 2.0.x). It was not intended for general use ... hence www.phpbb.com will not make available template sets which include PHP. And by default templates will have PHP disabled (the admin will need to specifically activate PHP for a template).

Conditionals/Control structures

The most significant addition to 3.0.x are conditions or control structures, "if something then do this else do that". The system deployed is very similar to Smarty. This may confuse some people at first but it offers great potential and great flexibility with a little imagination. In their most simple form these constructs take the form:

<!-- IF expr -->
markup
<!-- ENDIF -->

expr can take many forms, for example:

<!-- IF loop.S_ROW_COUNT is even -->
markup
<!-- ENDIF -->

This will output the markup if the S_ROW_COUNT variable in the current iteration of loop is an even value (i.e. the expr is TRUE). You can use various comparison methods (standard as well as equivalent textual versions noted in square brackets) including:

== [eq]
!= [neq, ne]
<> (same as !=)
!== (not equivalent in value and type)
===  (equivalent in value and type)
> [gt]
< [lt]
>= [gte]
<= [lte]
&& [and]
|| [or]
% [mod]
! [not]
+
-
*
/
<< (bitwise shift left)
>> (bitwise shift right)
| (bitwise or)
^ (bitwise xor)
& (bitwise and)
~ (bitwise not)
is (can be used to join comparison operations)

Basic parenthesis can also be used to enforce good old BODMAS rules. Additionally some basic comparison types are defined:

even
odd
div

Beyond the simple use of IF you can also do a sequence of comparisons using the following:

<!-- IF expr1 -->
markup
<!-- ELSEIF expr2 -->
markup
.
.
.
<!-- ELSEIF exprN -->
markup
<!-- ELSE -->
markup
<!-- ENDIF -->

Each statement will be tested in turn and the relevant output generated when a match (if a match) is found. It is not necessary to always use ELSEIF, ELSE can be used alone to match "everything else".

So what can you do with all this? Well take for example the colouration of rows in viewforum. In 2.0.x row colours were predefined within the source as either row color1, row color2 or row class1, row class2. In 3.0.x this is moved to the template, it may look a little daunting at first but remember control flows from top to bottom and it's not too difficult:

<table>
	<!-- IF loop.S_ROW_COUNT is even -->
	<tr class="row1">
	<!-- ELSE -->
	<tr class="row2">
	<!-- ENDIF -->
	<td>HELLO!</td>
</tr>
</table>

This will cause the row cell to be output using class row1 when the row count is even, and class row2 otherwise. The S_ROW_COUNT parameter gets assigned to loops by default. Another example would be the following:

<table>
	<!-- IF loop.S_ROW_COUNT > 10 -->
	<tr bgcolor="#FF0000">
	<!-- ELSEIF loop.S_ROW_COUNT > 5 -->
	<tr bgcolor="#00FF00">
	<!-- ELSEIF loop.S_ROW_COUNT > 2 -->
	<tr bgcolor="#0000FF">
	<!-- ELSE -->
	<tr bgcolor="#FF00FF">
	<!-- ENDIF -->
	<td>hello!</td>
</tr>
</table>

This will output the row cell in purple for the first two rows, blue for rows 2 to 5, green for rows 5 to 10 and red for remainder. So, you could produce a "nice" gradient effect, for example.

What else can you do? Well, you could use IF to do common checks on for example the login state of a user:

<!-- IF S_USER_LOGGED_IN -->
markup
<!-- ENDIF -->

This replaces the existing (fudged) method in 2.0.x using a zero length array and BEGIN/END.

Top