Naming convention

Gentics Portal.Node PHP uses PEAR coding standards.

1 Indenting and Line Length

Use an indent of 4 spaces, with no tabs. This helps to avoid problems with diffs, patches, code versioning history and annotations.

2 Control Structures

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


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

Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls.

You are strongly encouraged to always use curly braces even in situations where they are technically optional. Having them increases readability and decreases the likelihood of logic errors being introduced when new lines are added.

For switch statements:


<?php
switch (condition) {
case 1:
    action1;
    break;

case 2:
    action2;
    break;

default:
    defaultaction;
    break;
}
?>

Split long if-statements onto several lines

Long if-statements may be split onto several lines when the character/line limit would be exceeded. The conditions have to be positioned onto the following line, and indented 4 characters. The logical operators (&&, ||, etc.) should be at the beginning of the line to make it easier to comment (and exclude) the condition. The closing parenthesis and opening brace get their own line at the end of the conditions.

Keeping the operators at the beginning of the line has two advantages: It is trivial to comment out a particular line during development while keeping syntactically correct code (except of course the first line). Further is the logic kept at the front where it’s not forgotten. Scanning such conditions is very easy since they are aligned below each other.


<?php

if (($condition1
    || $condition2)
    && $condition3
    && $condition4
) {
    //code here
}
?>

The first condition may be aligned to the others.


<?php

if (   $condition1
    || $condition2
    || $condition3
) {
    //code here
}
?>

The best case is of course when the line does not need to be split. When the if-clause is really long enough to be split, it might be better to simplify it. In such cases, you could express conditions as variables an compare them in the if-condition. This has the benefit of “naming” and splitting the condition sets into smaller, better understandable chunks:


<?php

$is_foo = ($condition1 || $condition2);
$is_bar = ($condition3 && $condtion4);
if ($is_foo && $is_bar) {
    // ....
}
?>

There were suggestions to indent the parantheses “groups” by 1 space for each grouping. This is too hard to achieve in your coding flow, since your tab key always produces 4 spaces. Indenting the if-clauses would take too much finetuning.

3 Ternary operators

The same rule as for if-clauses also applies for the ternary operator: It may be split onto several lines, keeping the question mark and the colon at the front.


<?php

$a = $condition1 && $condition2
    ? $foo : $bar;

$b = $condition3 && $condition4
    ? $foo_man_this_is_too_long_what_should_i_do
    : $bar;
?>

4 Function Calls

Functions should 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:


<?php
$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:


<?php
$short         = foo($bar);
$long_variable = foo($baz);
?>

To support readability, parameters in subsequent calls to the same function/method may be aligned by parameter name:


<?php

$this->callSomeFunction('param1',     'second',        true);
$this->callSomeFunction('parameter2', 'third',         false);
$this->callSomeFunction('3',          'verrrrrrylong', true);
?>

Split function call on several lines

The CS require lines to have a maximum length of 80 chars. Calling functions or methods with many parameters while adhering to CS is impossible in that cases. It is allowed to split parameters in function calls onto several lines.


<?php

$this->someObject->subObject->callThisFunctionWithALongName(
    $parameterOne, $parameterTwo,
    $aVeryLongParameterThree
);
?>

Several parameters per line are allowed. Parameters need to be indented 4 spaces compared to the level of the function call.

The opening parenthesis is to be put at the end of the function call line, the closing parenthesis gets its own line at the end of the parameters. This shows a visual end to the parameter indentations and follows the opening/closing brace rules for functions and conditionals.

The same applies not only for parameter variables, but also for nested function calls and for arrays.


<?php

$this->someObject->subObject->callThisFunctionWithALongName(
    $this->someOtherFunc(
        $this->someEvenOtherFunc(
            'Help me!',
            array(
                'foo'  => 'bar',
                'spam' => 'eggs',
            ),
            23
        ),
        $this->someEvenOtherFunc()
    ),
    $this->wowowowowow(12)
);
?>

Nesting those function parameters is allowed if it helps to make the code more readable, not only when it is necessary when the characters per line limit is reached.

Using fluent application programming interfaces often leads to many concatenated function calls. Those calls may be split onto several lines. When doing this, all subsequent lines are indented by 4 spaces and begin with the “→” arrow.


<?php

$someObject->someFunction("some", "parameter")
    ->someOtherFunc(23, 42)
    ->andAThirdFunction();
?>

5 Alignment of assignments

To support readability, the equal signs may be aligned in block-related assignments:


<?php

$short  = foo($bar);
$longer = foo($baz);
?>

The rule can be broken when the length of the variable name is at least 8 characters longer/shorter than the previous one:


<?php

$short = foo($bar);
$thisVariableNameIsVeeeeeeeeeeryLong = foo($baz);
?>

Split long assigments onto several lines

Assigments may be split onto several lines when the character/line limit would be exceeded. The equal sign has to be positioned onto the following line, and indented by 4 characters.


<?php

$GLOBALS['TSFE']->additionalHeaderData[$this->strApplicationName]
    = $this->xajax->getJavascript(t3lib_extMgm::siteRelPath('nr_xajax'));
?>

6 Class Definitions

Class declarations have their opening brace on a new line:


<?php
class Foo_Bar
{

    //... code goes here

}
?>

7 Function Definitions

Function declarations follow the “K&R style”:


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

Arguments with default values go at the end of the argument list. Always attempt to return a meaningful value from a function if one is appropriate. Here is a slightly longer example:


<?php
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;
}
?>

Split function definitions onto several lines

Functions with many parameters may need to be split onto several lines to keep the 80 characters/line limit. The first parameters may be put onto the same line as the function name if there is enough space. Subsequent parameters on following lines are to be indented 4 spaces. The closing parenthesis and the opening brace are to be put onto the next line, on the same indentation level as the “function” keyword.


<?php

function someFunctionWithAVeryLongName($firstParameter = 'something', $secondParameter = 'booooo',
    $third = null, $fourthParameter = false, $fifthParameter = 123.12,
    $sixthParam = true
) {
    //....
?>

8 Arrays

Assignments in arrays may be aligned. When splitting array definitions onto several lines, the last value may also have a trailing comma. This is valid PHP syntax and helps to keep code diffs minimal:


<?php

$some_array = array(
    'foo'  => 'bar',
    'spam' => 'ham',
);
?>

9 Comments

Complete inline documentation comment blocks (docblocks) must be provided. Please read the Sample File and Header Comment Blocks sections of the Coding Standards to learn the specifics of writing docblocks for PEAR packages. Further information can be found on the phpDocumentor website.

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 fine. Use of Perl/shell style comments (#) is discouraged.

10 Including Code

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.

include_once and require_once are statements, not functions. Parentheses should not surround the subject filename.

11 PHP Code Tags

Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for PEAR compliance and is also the most portable way to include PHP code on differing operating systems and setups.

12 Header Comment Blocks

All source code files in the PEAR repository shall contain a “page-level” docblock at the top of each file and a “class-level” docblock immediately above each class. Below are examples of such docblocks.


<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Short description for file
 *
 * Long description for file (if any)...
 *
 * PHP version 5
 *
 * LICENSE: This source file is subject to version 3.01 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_01.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 * @category   CategoryName
 * @package    PackageName
 * @author     Original Author <author@example.com>
 * @author     Another Author <another@example.com>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version    SVN: $Id$
 * @link       http://pear.php.net/package/PackageName
 * @see        NetOther, Net_Sample::Net_Sample()
 * @since      File available since Release 1.2.0
 * @deprecated File deprecated in Release 2.0.0
 */

/*
* Place includes, constant defines and $_GLOBAL settings here.
* Make sure they have appropriate docblocks to avoid phpDocumentor
* construing they are documented by the page-level docblock.
*/

/**
 * Short description for class
 *
 * Long description for class (if any)...
 *
 * @category   CategoryName
 * @package    PackageName
 * @author     Original Author <author@example.com>
 * @author     Another Author <another@example.com>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version    Release: @package_version@
 * @link       http://pear.php.net/package/PackageName
 * @see        NetOther, Net_Sample::Net_Sample()
 * @since      Class available since Release 1.2.0
 * @deprecated Class deprecated in Release 2.0.0
 */
class Foo_Bar
{
}

?>

Required Tags That Have Variable Content

12.1 Short Descriptions

Short descriptions must be provided for all docblocks. They should be a quick sentence, not the name of the item. Please read the Coding Standard’s Sample File about how to write good descriptions.

@link

The following must be used in both the page-level and class-level docblocks. Of course, change “PackageName” to the name of your package. This ensures the generated documentation links back your package.

@author

There’s no hard rule to determine when a new code contributor should be added to the list of authors for a given source file. In general, their changes should fall into the “substantial” category (meaning somewhere around 10% to 20% of code changes). Exceptions could be made for rewriting functions or contributing new logic.

Simple code reorganization or bug fixes would not justify the addition of a new individual to the list of authors.

@since

This tag is required when a file or class is added after the package’s initial release. Do not use it in an initial release.

@deprecated

This tag is required when a file or class is no longer used but has been left in place for backwards compatibility.

13 Naming Conventions

13.1 Global Variables and Functions

If your package needs to define global variables, their names should start with a single underscore followed by the package name and another underscore. For example, the PEAR package uses a global variable called $_PEAR_destructor_object_list.

Global functions should be named using the “studly caps” style (also referred to as “bumpy case” or “camel caps”). In addition, they should have the package name as a prefix, to avoid name collisions between packages. The initial letter of the name (after the prefix) is lowercase, and each letter that starts a new “word” is capitalized. An example:

XML_RPC_serializeData()

13.2 Classes

Classes should be given descriptive names. Avoid using abbreviations where possible. Class names should always begin with an uppercase letter. The PEAR class hierarchy is also reflected in the class name, each level of the hierarchy separated with a single underscore.

Examples of good class names are:

  • Log
  • Net_Finger
  • HTML_Upload_Error

13.3 Class Variables and Methods

Class variables (a.k.a properties) and methods should be named using the “studly caps” style (also referred to as “bumpy case” or “camel caps”).

Some examples (these would be “public” members):

  • $counter
  • connect()
  • getData()
  • buildSomeWidget()

Private class members are preceded by a single underscore. For example:

  • $_status
  • _sort()
  • _initTree()

13.4 The following applies to PHP5.

Protected class members are not preceded by a single underscore. For example:

  • protected $somevar
  • protected function initTree() h4(#constants). 13.5 Constants

Constants should always be all-uppercase, with underscores to separate words.

Prefix constant names with the uppercased name of the class/package they are used in.

Some examples:

  • DB_DATASOURCENAME
  • SERVICES_AMAZON_S3_LICENSEKEY