wiki:Convention_de_codage

Cette page est un copier/coller de ce qui se trouve sur le forum, même pas entièrement wikifié

Ceci est un premier jet, et une traduction incomplète, les suggestions sont les bienvenues

Inspiré de gforge

  1. Commentaires

Guidelines

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.

  • C++ style comments (/* */) and standard C comments () are both acceptable.
  • Use of perl/shell style comments (#) is prohibited.

PHPdoc Tags

Inline documentation for classes should follow the PHPDoc convention, similar to Javadoc. More information about PHPDoc can be found here:

http://www.phpdoc.de/

File Comments:

Every file should start with a comment block describing its purpose, version, author and a copyright message. The comment block should be a block comment in standard JavaDoc format along with a CVS Id tag. While all JavaDoc tags are allowed, only the tags in the examples below will be parsed by PHPdoc.

Tous les fichier de nainwak doivent porter la mention de copyright de l'association:

/**
 *
 * brief description.
 * long description.  more long description.
 *
 * @author Haiken
 * @author Codeur phantome <on.ne.saura.jamais@nainwak.com>
 * @copyright 2002-2005 (c) association Nainwak
 *
 * @version  Reloaded 1.0
 *
 */

Function and Class Comments:

Similarly, every function should have a block comment specifying name, parameters, return values, and last change date.

/**
 * brief description.
 * long description.  more long description.
 *
 * @author    firstname lastname email
 * @param     variable  description
 * @return    value     description
 * @date      YYYY-MM-DD
 * @deprecated
 * @see
 *
 */

Note

The placement of periods in the short and long descriptions is important to the PHPdoc parser. The first period always ends the short description. All future periods are part of the long description, ending with a blank comment line. The long comment is optional.

  1. Formatting

Indentation

Toute l'indentation doit être faite avec 2 espaces et sans tabulation.

Les balises PHP

Il est impératif de délimiter le code PHP avec <?php ?> . L'usage de <? ?> est incorrect. C'est la manière la plus portable d'inclure du code PHP. De plus, les parseurs XML peuvent être trompés avec la syntaxe courte.

  1. Expressions
  • Use parentheses liberally to resolve ambiguity.
  • Using parentheses can force an order of evaluation. This saves the time a reader may spend remembering precedence of operators.
  • Don't sacrifice clarity for cleverness.
  • Write conditional expressions so that they read naturally aloud.
  • Sometimes eliminating a not operator (!) will make an expression more understandable.
  • Keep each line simple.
  • The ternary operator (x ? 1 : 2) usually indicates too much code on one line. if… else if… else is usually more readable.
  1. Functions

Function Calls

Functions shall be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here's an example:

$var = foo($bar, $baz, $quux);

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

Définition des Fonctions

Les déclaration de fonction doivent suivre la convention unix:

function fooFunction($arg1, $arg2 = '') {
    if (condition) 
   {
        statement;
    }
    return $val;
}

Les Arguments avec de valeurs par défaut vont à la fin de la liste d'arguments. Lorsque c'est approprié, les fonctions doivent toujours renvoyer une valeur significative. Un example un peu plus long:

function connect(&$dsn, $persistent = false) {
    if (is_array($dsn))
    {
        $dsninfo = &$dsn;
    } else 
    {
        $dsninfo = DB::parseDSN($dsn);
    }

    if (!$dsninfo || !$dsninfo['phptype'])
    {
        return $this->raiseError();
    }
    return true;
}
  1. Objects

Objects should generally be "normalized" similar to a database so they contain only the attributes that make sense.

Each object should have Error.class as the abstract parent object unless the object or its subclasses will never produce errors.

Each object should also have a create() method which does the work of inserting a new row into the database table that this object represents.

An update() method is also required for any objects that can be changed. Individual set() methods are generally not a good idea as doing separate updates to each field in the database is a performance bottleneck.

fetchData() and getId() are also standard in most objects. See the tracker codebase for specific examples.

Common sense about performance should be used when designing objects.

  1. Naming
  • Constants should always be uppercase, with underscores to separate words. Prefix constant names with the name of the class/package they are used in. For example, the constants used by the DB:: package all begin with "DB_".
  • True and false are built in to the php language and behave like constants, but should be written in lowercase to distinguish them from user-defined constants.
  • Function names should suggest an action or verb: updateAddress, makeStateSelector
  • Variable names should suggest a property or noun: UserName, Width
  • Use pronounceable names. Common abbreviations are acceptable as long as they are used the same way throughout the project.
  • Be consistent, use parallelism. If you are abbreviating number as 'num', always use that abbreviation. Don't switch to using no or nmbr.
  • Database tables should be named with underscores _ between words like: my_table and indexes on tables should be named with the table name first with the underscores removed, then field names mytable_field1field2.
  • Use descriptive names for variables used globally, use short names for variables used locally.
      $AddressInfo = array(...);

      for($i=0; $i < count($list); $i++)
  1. Structures de contrôle

These include if, for, while, switch, etc. Here is an example if statement, since it is the most complicated form:

if ((condition1) || (condition2))
{
    action1;
} elseif ((condition3) && (condition4))
{
    action2;
} else
{
    defaultaction;
}

Les structures de controle devraient avoir une espace entre le mot clef et la parenthèse ouvrante, afin de les distinguer des appels de fonction.

Vous devez impérativement utiliser les accolades, même lorsque techniquement, elle ne sont pas requises. Leur présence augmente la lisibilité et réduit la probabilité que des erreurs de logique apparaissent à la suite d'ajout de lignes.

Pour la structure switch:

switch (condition)
{
    case 1:
    {
        action1;
        break;
    }
    case 2:
    {
        action2;
        break;
    }
    default:
    {
        defaultaction;
        break;
    }
}

La notation unix est tolérée, mais déconseillée, elle me semble moins claire ex:

switch (condition) {
    case 1: {
        action1;
        break;
    }
    case 2: {
        action2;
        break;
    }
    default: {
        defaultaction;
        break;
    }
}
  1. Including PHP Files

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 keywords, not functions. Les parenthèses autour du nom de fichier à inclure sont facultatives, ceci dit il est fortement recommandé de les mettre. De plus, utilisez des ' (apostrophes) et non pas des " (guillemets):

include_once('pre.php');
  1. Structure du code

ça va viendre

  1. Requêtes (My)SQL

Petit Ajout pour Mysql: Il est important d'utiliser toujours la même syntaxe avec mysql car dans le cas contraire, ce dernier est incapable de metre les requêtes en cache.

Par exemple:

SELECT * FROM BANIP

est différant de

select * from BANIP

pour la cache de requête de mysql.

Je recommande donc d'utiliser systématiquement la casse telle que proposée par phpMyAdmin, c'est à dire avec les mots clefs en majuscules, après avoir supprimé les éventuel retours à la ligne. Ceci afin d'avoir une casse consistante. De plus c'est un bon moyen de vérifier au passage que cette requête est a peu près optimisée (cf EXPLAIN).

  1. Une petite illustration marrante

http://poisonedminds.com/comics/pm20060621.png

Last modified 18 years ago Last modified on Jul 7, 2006, 10:18:01 PM
Note: See TracWiki for help on using the wiki.