Manual:Coding conventions/PHP/fr

Cette page décrit les conventions de codage utilisées pour les fichiers de la écrits en PHP. Voir aussi les qui s'appliquent à tous les langages de programmation, y compris PHP. Si vous désirez un résumé des éléments à vérifier lorsque vous faites vos validations (submit), voyez la.

Pour aider les développeurs à corriger leur code du point de vue répartition des espaces, il existe l'outil stylize, qui vérifie la syntaxe réellement et ajoute les espaces aux endroits nécessaires; cet outil est également disponible via un interface web. Il est recommandé de l'exécuter avant de valider les fichiers dans Git.

Les règles pour PHP_CodeSniffer sont aussi disponibles. Pour plus d'informations, voir. Le dépôt Git  contient les paramètres de PHP_CodeSniffer pour le code MediaWiki.

Espaces
MediaWiki encourage un style bien structuré au niveau des espaces pour une lisibilité optimale.

Placez les espaces de chaque côté des opérateurs binaires, par exemple :

Places les espaces à côté de l'intérieur des parenthèses, sauf si elles sont vides. Ne mettez pas d'espace après un nom de fonction.

Placez les espaces à l'intérieur des crochets lorsque vous déclarez un tableau, sauf si le tableau est vide. Ne mettez pas d'espace dans les crochets lorsque vous accédez aux éléments d'un tableau.

Les structures de contrôle telles que, , , , , ainsi que le mot clé , doivent être suivies d'un espace :

Lorsque le 'cast' est appliqué sur un type, ne mettez pas d'espace à l'intérieur ni après l'opérateur cast :

Dans les commentaires, il doit y avoir un espace entre le caractère (ou ) et le commentaire lui-même.

Pour aider les développeurs à corriger le code du point de vue de l'emplacement des espaces, il existe l'outil stylize qui ajoute automatiquement des caractères d'après les conventions PHP. Cet outil est disponible via l'interface web.

Opérateur ternaire
Le peut être utilisé à profit si les expressions sont très courtes et triviales :

But if you're considering a multi-line expression with a ternary operator, please consider using an block instead. Remember, disk space is cheap, code readability is everything, "if" is English and  is not. If you are using a multi-line ternary expression, the question mark and colon should go at the beginning of the second and third lines and not the end of the first and second (in contrast to MediaWiki's Javascript convention).

Since MediaWiki requires PHP or later, use of the shorthand ternary operator  also known as the elvis operator, introduced in PHP 5.3, is allowed.

Since PHP 7.0 the null coalescing operator is also available and can replace the ternary operator in some use cases. For example, instead of you could instead write the following:

Chaînes de caractères
Single quotes are preferred in all cases where they are equivalent to double quotes. Code using single quotes is less error-prone and easier to review, as it can not accidentally contain escape sequences or variables. For example, the regular expression requires an extra backslash, making it slightly more confusing and error-prone than. Also for people using US/UK qwerty keyboards, they are easier to type, since it avoids the need to press shift.

Néanmoins, n'ayez pas peur d'utiliser la fonctionalité PHP d'interpolation des chaînes à double apostrophes :

Ceci a des caractéristiques de performance quelque peu meilleures que l'équivalent utilisant l'opérateur de concatenation '.' (dot), et c'est aussi plus joli.

Heredoc-style strings are sometimes useful:

Some authors like to use END as the ending token, which is also the name of a PHP function. This leads to IRC conversations like the following:

Fonctions et paramètres
Evitez de passer un trop grand nombre de paramètres aux fonctions at aux constructeurs :

It quickly becomes impossible to remember the order of parameters, and you will inevitably end up having to hardcode all the defaults in callers just to customise a parameter at the end of the list. If you are tempted to code a function like this, consider passing an associative array of named parameters instead.

In general, using boolean parameters is discouraged in functions. In, without looking up the documentation for , it is impossible to know what those parameters are meant to indicate. Much better is to either use class constants, and make a generic flag parameter:



Ou pour que votre fonction accepte un tableau de paramètres nommés :



Try not to repurpose variables over the course of a function, and avoid modifying the parameters passed to a function (unless they're passed by reference and that's the whole point of the function, obviously).

Expressions d'assignement
Using assignment as an expression is surprising to the reader and looks like an error. Do not write code like this:

L'espace n'est pas cher et vous écrivez rapidement, utilisez donc à la place :

Utiliser l'assignation dans une boucle est légitime pour l'itération :

Ceci est inutile dans le nouveau code; remplacez par :

Emprunts au langage C
The PHP language was designed by people who love C and wanted to bring souvenirs from that language into PHP. But PHP has some important differences from C.

In C, constants are implemented as preprocessor macros and are fast. In PHP, they are implemented by doing a runtime hashtable lookup for the constant name, and are slower than just using a string literal. In most places where you would use an enum or enum-like set of macros in C, you can use string literals in PHP.

PHP has three special literals for which upper-/lower-/mixed-case is insignificant in the language (since PHP 5.1.3), but for which our convention is always lowercase:, and.

Use not. They have subtly different meanings:

Et le dernier a de piètres performances.

Syntaxe alternative pour les structures de contrôle
PHP offre une sntaxe alternative pour les structures de contrôle en utilisant des points-virgule ';' et des mots-clés tels que,  , etc. :

Cette syntaxe doit être évitée car elle empêche beaucoup d'éditeurs de texte de faire correspondre et refermer automatiquement les accolades. Les accolades doivent être utilisées à la place :

Placement des parenthèses
Voir indentation et alignement.

Déclarations de type dans les paramètres de fonction
Utilisez les déclarations de type et les déclarations du type retourné (type hinting) si nécessaire.

Notez que avant 7.4 PHP ne pouvait pas gérer la restriction/relaxation du type retourné dans les sous-classes.

Nommage
Utilisez les minuscules alternées (lowerCamelCase) pour les noms de fonction ou de variable. Par exemple : Utilisez des majuscules alternées (UpperCamelCase) pour les noms des classes :. Utilisez des majuscules avec des caractères souligné '_' pour les constantes de classe et globales :,. Les autres variables sont habituellement en minuscules ou en lowerCamelCase; évitez d'utiliser les soulignés dans les noms de variables.

Il existe aussi des préfixes utilisés à différents endroits :

Fonctions

 * (fonctions wiki) – fonctions de niveau général, par exemple
 * (fonctions d'extensions) = global functions in extensions, although "in most cases modern style puts hook functions as static methods on a class, leaving few or no raw top-level functions to be so named." (-- brion in Manual_talk:Coding_conventions)

Verb phrases are preferred: use instead of.

Variables

 * – global variables, e.g., . Always use this for new globals, so that it's easy to spot missing "" declarations. In extensions, the extension name should be used as a namespace delimiter. For example, , not.
 * Global declarations should be at the beginning of a function so dependencies can be determined without having to read the whole function.

It is common to work with an instance of the  class; we have a naming convention for these which helps keep track of the nature of the server to which we are connected. This is of particular importance in replicated environments, such as Wikimedia and other large wikis; in development environments, there is usually no difference between the two types, which can conceal subtle errors.


 * – a  object for writing (a master connection)
 * – a  object for non-concurrency-sensitive reading (this may be a read-only slave, slightly behind master state, so don't ever try to write to the database with it, or get an "authoritative" answer to important queries like permissions and block status)

The following may be seen in old code but are discouraged in new code:


 * – Variables de session, par exemple
 * – Variables de cookies, par exemple
 * – Variables postées (envoyées par les champs de formulaire), par exemple
 * – variables membres d'objets : . Ceci n'est pas du tout recommandé dans le nouveau code, mais essayez de rester cohérent à l'intérieur d'une même classe.

The function should only be used when you want to suppress errors. Otherwise just use  (boolean conversion).

Common use case: Optional boolean configuration keys that default to false.
 * essentially does.


 * Beware of boolean conversion pitfalls.
 * It suppresses errors about undefined properties and variables. If only intending to test for undefined, use . If only intending to test for "empty" values (e.g. false, zero, empty array, etc.), use.

Do not use to test for. Using in this situation could introduce errors by hiding misspelled variable names. Instead, use.

Conversion booléenne

 * Do not use  or  to test if a string or array is empty, because PHP considers    to be falsy – but   is a valid title and valid user name in MediaWiki. Use   or   instead.
 * Study the rules for conversion to boolean. Be careful when converting strings to boolean.

Autre

 * Array plus does not renumber the keys of numerically-indexed arrays, so . If you want keys to be renumbered, use :
 * Make sure you have set to  . This will notify you of undefined variables and other subtle gotchas that stock PHP will ignore. See also Manual:How to debug.
 * When working in a pure PHP file (e.g. not an HTML template), omit any trailing  tags. These tags often cause issues with trailing white-space and "headers already sent" error messages (cf. 17642 and http://news.php.net/php.general/280796). It is conventional in version control for files to have a new line at end-of-file (which editors may add automatically), which would then trigger this error.
 * Do not use the syntax introduced in 5.3. PHP may have introduced the feature, but that does not mean we should use it.
 * Do not pass by reference when traversing an array unless you have to. Even then, be aware of the consequences. (See http://www.king-foo.be/2010/10/php-quirks-passing-an-array-by-reference/)
 * PHP lets you declare static variables even within a non-static method of a class. This has led to subtle bugs in some cases, as the variables are shared between instances. Where you would not use a  property, do not use a static variable either.

Opérateurs d'égalité
Faites attention avec les opérateurs de comparaison à double signe égal. Le triple-égal est généralement plus intuitif et doit être préféré, à moins que vous ayez une raison particulière d'utiliser le double-égal.


 * est vrai (!)
 * est vrai (!)
 * est faux
 * To check if two scalars that are supposed to be numeric are equal, use, e.g.  is true.
 * To check if two variables are both of type 'string' and are the same sequence of characters, use, e.g.  is false.

Précision des nombres JSON
JSON uses JavaScript's type system, so all numbers are represented as 64bit IEEE floating point numbers. This means that numbers lose precision when getting bigger, to the point where some whole numbers become indistinguishable: Numbers beyond 2^52 will have a precision worse than ±0.5, so a large integer may end up changing to a different integer. To avoid this issue, represent potentially large integers as strings in JSON.

Ne pas utiliser la construction lors de la sérialisation
PHP's built in serialization mechanism (the  and   functions) should not be used for data stored (or read from) outside of the current process. Use JSON based serialization instead (however, beware the pitfalls). This is policy established by RFC T161647.

The reason is twofold: (1) data serialized with this mechanism cannot reliably be unserialized with a later version of the same class. And (2) crafted serialized data can be used to execute malicious code, posing a serious security risk.

Sometimes, your code will not control the serialization mechanism, but will be using some library or driver that uses it internally. Dans de tels cas, il faut procéder par étapes pour réduire les risques. Le premier problème mentionné ci-dessus peut être évité en convertissant toute donnée en des tableaux ou des objets simples anonymes avant la sérialisation. The second issue can perhaps be mitigated using the whitelisting feature PHP 7 introduces for unserialization.

Commentaires et documentation
It is essential that your code be well documented so that other developers and bug fixers can easily navigate the logic of your code. New classes, methods, and member variables should include comments providing brief descriptions of their functionality (unless it is obvious), even if private. In addition, all new methods should document their parameters and return values.

We use the Doxygen documentation style (it is very similar to PHPDoc for the subset that we use) to produce auto-generated documentation from code comments (see Manual:mwdocgen.php). Begin a block of Doxygen comments with, instead of the Qt-style formatting. Doxygen structural commands start with. (Use  rather than   as the escape character – both styles work in Doxygen, but for backwards and future compatibility MediaWiki has chosen the   style.) They organize the generated documentation (using  ) and identify authors (using   tags).

They describe a function or method, the parameters it takes (using ), and what the function returns (using  ). The format for parameters is: @param type $paramName Description of parameter If a parameter can be of multiple types, separate them with the pipe '|' character, for example:

Continue sentences belonging to an annotation on the next line, indented with one additional space.

For every public interface (method, class, variable, whatever) you add or change, provide a  tag, so people extending the code via this interface know they are breaking compatibility with older versions of the code.

FIXME usually means something is bad or broken. TODO means that improvements are needed; it does not necessarily mean that the person adding the comment is going to do it. HACK means that a quick but inelegant, awkward or otherwise suboptimal solution to an immediate problem was made, and that eventually a more thorough rewrite of the code should be done.

Entêtes des fichiers source
In order to be compliant with most licenses you should have something similar to the following (specific to GPLv2 applications) at the top of every source file.

Balises Doxygen
We use the following annotations which Doxygen recognizes. Use them in this order, for consistency:

File level:
 * @file
 * @ingroup
 * @author

Class, class member, or global member:


 * @todo
 * @var
 * @deprecated
 * @class
 * @since
 * @param
 * @return
 * @throws
 * @private
 * @see

Annotations de test
In tests, we use the following annotations among others. These aren't merely documentation, they mean something to PHPUnit and affect test execution.


 * @depends
 * @group
 * @covers
 * @dataProvider
 * @expectedException
 * @expectedExceptionMessage

Intégration
There are a few pieces of code in the MediaWiki codebase which are intended to be standalone and easily portable to other applications. While some of these now exist as separate libraries, others remain within the MediaWiki source tree (e.g. the files in ). Apart from these, code should be integrated into the rest of the MediaWiki environment, and should allow other areas of the codebase to integrate with it in return.

Visibilité
Rendez les méthodes 'public', 'protected', ou 'private' (selon le rôle de la méthode). Réfléchissez : il ne s'agit pas de rendre tout 'public' !

Objets globaux
Do not access the PHP superglobals, , etc, directly; use > instead; there are various functions depending on what type of value you want.You can get a from the nearest , or if absolutely necessary. Equally, do not access directly; use  if you want to get the IP address of the current user.

Méthodes statiques et propriétés
Static methods and properties can be used in PHP, but care should be taken when inheriting to distinguish between the  and   keywords. will always refer to the class in which it was defined, whereas  will refer to the particular sub-class invoking it. See the PHP documentation on Late Static Bindings for more details.

Classes
Encapsulate your code in an object-oriented class, or add functionality to existing classes; do not add new global functions or variables. Try to be mindful of the distinction between 'backend' classes, which represent entities in the database (eg,  ,  , etc), and 'frontend' classes, which represent pages or interfaces visible to the user ( ,  ,  , etc. Even if your code is not obviously object-oriented, you can put it in a static class (eg   or  ).

As a holdover from PHP 4's lack of private class members and methods, older code will be marked with comments such as to indicate the intention; respect this as if it were enforced by the interpreter.

Mark new code with proper visibility modifiers, including if appropriate, but do not add visibility to existing code without first checking, testing and refactoring as required. It's generally a good idea to avoid visibility changes unless you're making changes to the function which would break old uses of it anyway.

Gestion des erreurs
Don't suppress errors with PHP's operator, for any reason ever. It's broken when  is enabled and it causes an unlogged, unexplained error if there is a fatal, which is hard to support.

The proper method of handling errors is to actually handle the errors. For example, if you are thinking of using an error suppression operator to suppress an invalid array index warning, you should instead perform an check on the array index before trying to access it. When possible, always prevent PHP errors rather than catching and handling them afterwards. It makes the code more understandable and avoids dealing with slow error suppression methods.

If and only if there is a situation where you are expecting an unavoidable PHP warning, you may use  and   from the at-ease library instead of the   operator. This is for cases where:


 * 1) Il est impossible d'anticiper l'erreur qui va arriver, et
 * 2) Vous envisagez de gérer l'erreur de manière appropriée une fois qu'elle est arrivée.

An example of this is opening a file with. You can anticipate the error by calling  and , but it is possible the file will have been deleted in between the check and the actual   call. In this case, your code should be ready to handle the case that the file will fail to open, and you can use  to prevent PHP from being noisy. Note that using  and   are slow. They are much slower than using the  operator, since it involves at least four function calls and reference counting, rather than just an opcode.

When your code encounters a sudden error, you should throw an exception rather than using PHP's. The exception handler will display this as nicely as possible to the end user and wiki administrator, and also provides a stack trace to developers. Don't throw an instance of Exception itself, but instead a subclass of it. Exceptions that indicate programming errors should be one of the exceptions that ship with PHP or a more specific subclass, while exceptions that indicate errors that are relevant to the end user should be an ErrorPageError or one of its subclasses.