Coding guidelines

These conventions are partly copied from PhpBB coding style convention.

Editor Settings

Tabs vs Spaces: In order to make this as simple as possible, we will be using spaces, not tabs.

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 Win32 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.

A good idea is to make sure that eol-style svn property is set to native on svn server. If the case, the editor does not matter as svn (or tortoise) will automatically do the translation UNIX↔DOS. To do that, type “svn propset eol-style native MyFile”. You can also make sure all new files are added with the correct property by having the following lines in your subversion configuration file:

[miscellany]
enable-auto-props = yes
[auto-props]
*.php = svn:eol-style=LF
*.tpl = svn:eol-style=LF
*.css = svn:eol-style=LF

Naming Conventions

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().

Code Layout

Standard header for new files: Here is a template of the header that must be included at the start of all PhpWebGallery files:

<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based picture gallery                                  |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2010 Piwigo Team                  http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify  |
// | it under the terms of the GNU General Public License as published by  |
// | the Free Software Foundation                                          |
// |                                                                       |
// | This program is distributed in the hope that it will be useful, but   |
// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
// | General Public License for more details.                              |
// |                                                                       |
// | You should have received a copy of the GNU General Public License     |
// | along with this program; if not, write to the Free Software           |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA.                                                                  |
// +-----------------------------------------------------------------------+

Always include the braces: This is another case of being too lazy to type 2 extra characters causing problems with code clarity. 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();
}

One line test: do not use a one line “if” statement, always use a next line.

/* Wrong */
if (condition) { do_stuff(); }
/* Right */
if (condition)
{
  do_stuff();
}

Where to put the braces: 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 
{
  ...
}

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 (many occurences must be modified in actual code, 2004-06-19). 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) and ($j > 8)) ...
 
do_stuff( $i, "foo", $b );
do_stuff($i, "foo", $b);
 
for($i=0; $i<$size; $i++) ...
for($i = 0; $i < $size; $i++) ...

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, examples:

/* what's the result? who knows. */
 
$bool = ($i < 7 and $j > 8 or $k == 4);
 
/* now you can be certain what I'm doing here. */
 
$bool = (($i < 7) and (($j < 8) or ($k == 4)))

SQL code layout: An SQL query always starts with a line break and the SQL code has its own indentation, so don't mix with PHP indentation. Here's a sample of how SQL code should look. Note where the lines break, the capitalization, examples:

if ($variable <= 0)
{
  if (0 == $variable)
  {
    $query = '
SELECT
    file,
    tn_ext,
    date_available,
    storage_category_id
  FROM '.IMAGES_TABLE.'
    JOIN '.IMAGE_CATEGORY_TABLE.' ON id = image_id
  WHERE storage_category_id IS NOT NULL
    AND date_available = \''.$calendar_day.'\'
  ORDER BY RAND()
  LIMIT 0,1
;';
  }
}

General Guidelines

line length: code lines (except in templates) must not exceed 79 characters. Please respect this simple convention.

operators (&&,and,||,or): always use “and” and “or” instead of ”&&” and “||”.

boolean conditions: since it changes in every programming language, do not test integer variable like if ($int_var). Always make test returning boolean values :

/* Wrong */
$test = 0;
if ( $test ) ...
/* Right */
if (0 == $test)...
 
$test = true;
if ( $test ) ...

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 harder 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);

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 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. Nobody should have to look at the actual source of a function in order to be able to call it with confidence in their own code.

In addition, commenting any tricky, obscure, or otherwise not-immediately-obvious code is clearly something we should be doing. Especially important to document are any assumptions your 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.

I'd like to use phpdocumentor to generate documentation, here is an example of good function comment :

/**
 * Is the category accessible to the connected user ?
 *
 * Note : if the user is not authorized to see this category, page creation
 * ends (exit command in this function)
 *
 * @param int category id to verify
 * @return void
 */
function check_restrictions( $category_id )
{...

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. Included in this guideline is that we should be using the constants TRUE and FALSE in place of the literals 1 and 0 – even though they have the same values, it's more obvious what the actual logic is when you use the named constants.

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: Since PhpWebGallery 1.3, 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 an error. This will come up most often when checking which HTML form variables were passed. These errors can be avoided by using the built-in isset() function to check whether a variable has been set, examples:

/* Old way */
 
if ($forum) ...
 
/* New way */
 
if (isset($forum)) ...

Don't use PHP short tags: Many shared hosts set short_open_tag=0, as a consequence short hand openning tags will cause parsing error.

/* Bad */
<? /* code */ ?>
<?= $var ?>
 
/* Good */
<?php /* code */ ?>
<?php echo $var; ?>

Don't use array_push(): array_push is 50% slower than the brackets operator.

/* Bad */
array_push($table, $row);
 
/* Good */
$table[] = $row;

array_push is still slower for multiple insertions.

 
Back to top
dev/coding_conventions.txt · Last modified: 2013/10/19 18:03 by mistic100
 
 
twitter facebook google+ newsletter Donate Piwigo.org © 2002-2014 · Contact