Coding-Stil

< Namenskonventionen | Übersicht

Auf dieser Seite... (ausblenden)

  1.   1.  PHP Code-Abgrenzung
  2.   2.  Strings
    1.   2.1  String-Literale
  3.   3.  String-Literale mit Apostrophen
    1.   3.1  Variable Substitution
  4.   4.  String-Konkatenation
  5.   5.  Arrays
    1.   5.1  Numerisch indizierte Arrays
    2.   5.2  Assoziative Arrays
  6.   6.  Klassen
    1.   6.1  Klassendeklaration
    2.   6.2  Klassenvariablen
  7.   7.  Funktionen und Methoden
    1.   7.1  Deklaration von Funktionen und Methoden
    2.   7.2  Aufruf von Funktionen and Methoden
  8.   8.  Kontrollstrukturen
    1.   8.1  if/else/elseif
    2.   8.2  Switch
  9.   9.  Inline Documentation
    1.   9.1  Documentation Format
    2.   9.2  Files
    3.   9.3  Classes
    4.   9.4  Functions
  10. 10.  Templates

1.  PHP Code-Abgrenzung

PHP Code muß immer mit der kompletten Form des Standard-PHP Tags abgegrenzt sein:

Kurze Tags sind nur in Templates erlaubt. Für Dateien die nur PHP Code enthalten, darf das schließende Tag nie angegeben werden.

2.  Strings

2.1  String-Literale

Bei String-Literalen, wenn ein String also keine Variablen enthält, sollte immer das Apostroph "'" (single quote) verwendet werden um den String abzugrenzen:

$aString = 'Example String';

3.  String-Literale mit Apostrophen

Wenn ein String-Literal selbst Apostrophe enthält, ist es gestattet den String mit Anführungszeichen (double quotes) abzugrenzen. Das ist speziell für SQL-Anweisungen nützlich:

$sql = "SELECT `id`, `name` from `people` "
     . "WHERE `name`='Fred' OR `name`='Susan'";

Diese Syntax ist gegenüber dem Schützen des Apostrophs durch "\'" aus Gründen der besseren Lesbarkeit zu bevorzugen.

3.1  Variable Substitution

Variable substitution is permitted using either of these forms:

$greeting = "Hello $name, welcome back!";

$greeting = "Hello {$name}, welcome back!";

For consistency, this form is not permitted:

$greeting = "Hello ${name}, welcome back!";

4.  String-Konkatenation

Strings müssen mit dem "."-Operator konkateniert werden. Ein Leerzeichen muß immer vor und nach dem "." Operator eingefügt werden, um die Lesbarkeit zu erhöhen:

$company = 'Zend' . ' ' . 'Technologies';

Werden Strings mit dem "." Operator konkateniert, sollte die Anweisung in mehrere Zeilen umgebrochen werden, um die Lesbarkeit zu erhöhen. In diesen Fällen sollte jede folgende Zeile mit Leerraum aufgefüllt werden so das der "." Operator genau unterhalb des "=" Operators steht:

$sql = "SELECT `id`, `name` FROM `people` "
     . "WHERE `name` = 'Susan' "
     . "ORDER BY `name` ASC ";

5.  Arrays

5.1  Numerisch indizierte Arrays

Negative Indizes sind nicht gestattet. Ein solches Array darf mit einer nicht-negativen Zahl beginnen, es wird jedoch davon abgeraten.

Werden indizierte Arrays mehrzeilig mit Hilfe der "array"-Funktion definiert, muß ein Leerzeichen nach jeder Kommabegrenzung folgen, um die Lesbarkeit zu erhöhen:

$sampleArray = array(1, 2, 3, 'Zend', 'Studio');

Es ist gestattet, mehrzeilige indizierte Arrays mit der "array"-Funktion zu definieren. In diesem Fall, muß jede folgende Zeile mit Leerzeichen aufgefüllt werden so das der Beginn jeder Zeile ausgerichtet ist:

$sampleArray = array(1, 2, 3, 'Zend', 'Studio',
                     $a, $b, $c,
                     56.44, $d, 500);

5.2  Assoziative Arrays

Wenn assoziative Arrays mit der "array"-Funktion deklariert werden, ist das Umbrechen der Anweisung in mehrere Zeilen gestattet. In diesem Fall muß jede folgende Linie mit Leerraum aufgefüllt werden so das beide, der Schlüssel und der Wert, untereinander stehen:

$sampleArray = array(
    'firstKey'  => 'firstValue',
    'secondKey' => 'secondValue'
);

6.  Klassen

6.1  Klassendeklaration

Klassen müssen den Namenskonventionen entsprechend benannt werden.

Die Klammer sollte immer in der Zeile unter dem Klassennamen geschrieben werden.

Jede Klasse muß einen Dokumentationsblock haben der dem PHPDocumentor Standard entspricht.

Jeder Code in der Klasse muß mit vier Leerzeichen eingerückt sein.

Nur eine Klasse ist in jeder PHP Datei gestattet.

Das Platzieren von zusätzlichem Code in Klassendateien ist gestattet, aber es wird davon abgeraten.

Das folgende ist ein Beispiel einer gültige Klassendeklaration:

/**
 * Documentation Block Here
 */

class SampleClass
{
    // all contents of class
    // must be indented four spaces
}

6.2  Klassenvariablen

Klassenvariablen müssen entsprechend den Variablennamenskonventionen benannt werden.

Jede Variable die in der Klasse deklariert wird muß am Beginn der Klasse aufgelistet werden, vor der Deklaration von allen Methoden.

Das "var"-Schlüsselwort ist nicht gestattet. Klassenvariablen definieren ihre Sichtbarkeit durch die Verwendung der private, protected, oder public Modifikatoren. Öffentliche Klassenvariable (Sichtbarkeit "public") sind erlaubt, es wird aber zu Gunsten von Zugriffsmethoden (getter/setter) davon abgeraten.

7.  Funktionen und Methoden

7.1  Deklaration von Funktionen und Methoden

Funktionen müssen nach der Funktionsnamenskonvention benannt werden.

Methoden innerhalb von Klassen müssen immer ihre Sichtbarkeit durch Verwendung eines der private, protected, oder public Modifikatoren definieren.

Wie bei Klassen sollte die Klammer immer in der Zeile unterhalb des Funktionsnamens geschrieben werden. Leerzeichen zwischen dem Funktionsnamen und der öffnenden Klammer für die Argumente sind nicht erlaubt.

Von globalen Funktionen wird abgeraten.

Das folgende ist ein Beispiel einer gültigen Funktionsdeklaration in einer Klasse:

/**
 * Documentation Block Here
 */

class Foo
{
    /**
     * Documentation Block Here
     */

    public function bar()
    {
        // all contents of function
        // must be indented four spaces
    }
}

NOTE: Pass-by-reference is the only explicit parameter passing mechanism permitted in a method declaration.

/**
 * Documentation Block Here
 */

class Foo
{
    /**
     * Documentation Block Here
     */

    public function bar(&$baz)
    {}
}

Call-time pass-by-reference ist strikt verboten.

Der Rückgabewert darf nicht in Klammern stehen. Das kann die Lesbarkeit behindern und zusätzlich zu Fehlern führen, wenn eine Methode später auf Rückgabe durch Referenz geändert wird.

/**
 * Documentation Block Here
 */

class Foo
{
    /**
     * WRONG
     */

    public function bar()
    {
        return($this->bar);
    }

    /**
     * RIGHT
     */

    public function bar()
    {
        return $this->bar;
    }
}

7.2  Aufruf von Funktionen and Methoden

Wie bei Funktionsdeklaration darf zwischen Funktionsnamen und der öffnenden Klammer für die Argumente beim Funktionsaufruf kein Leerzeichen stehen.

Funktionsargumente sollten durch ein einzelnes trennendes Leerzeichen nach dem Komma getrennt werden. Das folgende ist ein Beispiel für einen gültigen Aufruf einer Funktion die drei Argumente benötigt:

threeArguments(1, 2, 3);

Call-time pass-by-reference is strictly prohibited.

In passing arrays as arguments to a function, the function call may include the "array" hint and may be split into multiple lines to improve readability. In such cases, the normal guidelines for writing arrays still apply:

threeArguments(array(1, 2, 3), 2, 3);

threeArguments(array(1, 2, 3, 'Zend', 'Studio',
                     $a, $b, $c,
                     56.44, $d, 500), 2, 3);

8.  Kontrollstrukturen

8.1  if/else/elseif

Control statements based on the if and elseif constructs must have a single space before the opening parenthesis of the conditional and a single space after the closing parenthesis.

Within the conditional statements between the parentheses, operators must be separated by spaces for readability. Inner parentheses are encouraged to improve logical grouping for larger conditional expressions.

The opening brace is written on the same line as the conditional statement. The closing brace is always written on its own line. Any content within the braces must be indented using four spaces.

if ($a != 2) {
    $a = 2;
}

For "if" statements that include "elseif" or "else", the formatting conventions are similar to the "if" construct. The following examples demonstrate proper formatting for "if" statements with "else" and/or "elseif" constructs:

if ($a != 2) {
    $a = 2;
} else {
   $a = 7;
}

if ($a != 2) {
    $a = 2;
} elseif ($a == 3) {
   $a = 4;
} else {
   $a = 7;
}

PHP allows statements to be written without braces in some circumstances. This coding standard makes no differentiation - all "if", "elseif" or "else" statements must use braces.

Use of the "elseif" construct is permitted but strongly discouraged in favor of the "else if" combination.

8.2  Switch

Control statements written with the "switch" statement must have a single space before the opening parenthesis of the conditional statement and after the closing parenthesis.

All content within the "switch" statement must be indented using four spaces. Content under each "case" statement must be indented using an additional four spaces.

switch ($numPeople) {
    case 1:
        break;

    case 2:
        break;

    default:
        break;
}

The construct default should never be omitted from a switch statement.

NOTE: It is sometimes useful to write a case statement which falls through to the next case by not including a break or return within that case. To distinguish these cases from bugs, any case statement where break or return are omitted should contain a comment indicating that the break was intentionally omitted.

9.  Inline Documentation

9.1  Documentation Format

All documentation blocks ("docblocks") must be compatible with the phpDocumentor format. Describing the phpDocumentor format is beyond the scope of this document. For more information, visit: http://phpdoc.org/

All class files must contain a "file-level" docblock at the top of each file and a "class-level" docblock immediately above each class. Examples of such docblocks can be found below.

9.2  Files

Every file that contains PHP code must have a docblock at the top of the file that contains these phpDocumentor tags at a minimum:

/**
 * Short description for file
 *
 * Long description for file (if any)...
 *
 * LICENSE: Some license information
 *
 * @author     Vorname Nachname <email>
 * @copyright  2008 Zend Technologies
 * @license    http://framework.zend.com/license   BSD License
 * @category   Stud.IP
*/

Optional tags:

/**
 * @package    calendar
 * @link       http://framework.zend.com/package/PackageName
 * @since      File available since Release 1.5.0
*/

9.3  Classes

Every class must have a docblock that contains these phpDocumentor tags at a minimum:

/**
 * Short description for class
 *
 * Long description for class (if any)...
 *
 */

Optional tags:

/**
 * @link       http://framework.zend.com/package/PackageName
 * @since      Class available since Release 1.5.0
 * @deprecated Class deprecated in Release 2.0.0
 */

9.4  Functions

Every function, including object methods, must have a docblock that contains at a minimum:

A description of the function

All of the arguments

All of the possible return values

It is not necessary to use the "@access" tag because the access level is already known from the "public", "private", or "protected" modifier used to declare the function.

If a function/method may throw an exception, use @throws for all known exception classes:

@throws exceptionclass [description]

10.  Templates

Für Templates gelten alle obigen Aussagen. Zusätzlich gelten aber folgende Regeln:

Bei Short-Tag-Zuweisungen muss nach dem eröffnenden und vor dem schließenden Tag genau ein Leerzeichen eingefügt werden:

<div class="<?= $css_class ?>"></div>

Semikola werden nicht verwendet.

Zur Steigerung der Lesbarkeit können die alternativen Kontrollstrukturen verwendet werden:

<? if (true) : ?>
...
<? else : ?>
...
<? endif ?>

<? foreach ($array() as $key => $value) : ?>
...
<? endforeach ?>

usw.

Dabei ist zu beachten, dass die Doppelpunkte mit je einem Leerzeichen umschlossen werden. Die abschließenden endif, endforeach usw. dürfen (genau wie bei den sonst üblichen {}) nicht mit einem Semikolon beendet werden.

Letzte Änderung am August 05, 2011, at 11:40 AM von tgloeggl.