Difference between revisions of "Coding style and standards"

From Joomla! Documentation

(Major revision bringing in new standard for 1.6)
(Add spelling note)
Line 5: Line 5:
  
 
Good coding standards are important in any development project, but particularly when multiple developers are working on the same project. Having coding standards helps ensure that the code is of high quality, has fewer bugs, and is easily maintained.
 
Good coding standards are important in any development project, but particularly when multiple developers are working on the same project. Having coding standards helps ensure that the code is of high quality, has fewer bugs, and is easily maintained.
 +
 +
First rule, if in doubt, ask.
  
 
== File Format ==
 
== File Format ==
Line 15: Line 17:
  
 
== Coding Standards ==
 
== Coding Standards ==
 +
 +
=== Spelling ===
 +
 +
Spelling of class, function, variable and constant names should generally be in accordance with British English rules (en_GB).  However, some exceptions to this are common programming names that align with the PHP API such as <code>$color</code>.
  
 
=== E_STRICT-compatible code ===
 
=== E_STRICT-compatible code ===

Revision as of 16:30, 16 October 2008

Copyedit.png
This Article Needs Your Help

This article is tagged because it NEEDS REVIEW. You can help the Joomla! Documentation Wiki by contributing to it.
More pages that need help similar to this one are here. NOTE-If you feel the need is satistified, please remove this notice.


remark: The following information has been copied from the old WIKI archive has not yet been reviewed. See: http://dev.joomla.org/component/option,com_jd-wiki/Itemid,/id,standards:coding/

Good coding standards are important in any development project, but particularly when multiple developers are working on the same project. Having coding standards helps ensure that the code is of high quality, has fewer bugs, and is easily maintained.

First rule, if in doubt, ask.

File Format[edit]

All files contributed to Joomla must:

  • Be stored as ASCII text
  • Use UTF-8 character encoding
  • Be Unix formatted
    • Lines must end only with a line feed (LF). Line feeds are represented as ordinal 10, octal 012 and hex 0A. Do not use carriage returns (CR) like Macintosh computers do or the carriage return/line feed combination (CRLF) like Windows computers do.

Coding Standards[edit]

Spelling[edit]

Spelling of class, function, variable and constant names should generally be in accordance with British English rules (en_GB). However, some exceptions to this are common programming names that align with the PHP API such as $color.

E_STRICT-compatible code[edit]

As of version 1.6, all new code that is suggested for inclusion into Joomla must be E_STRICT-compatible. This means that it must not produce any warnings or errors when PHP's error reporting level is set to E_ALL | E_STRICT.

Indenting and Line Length[edit]

Use tabs to indent, not spaces. Make sure that the tab-stops are set to only 4 spaces in length.

There is no set limit for line length 75-85 characters is a good target. Use your judgement based on the nature of the line and readability. Line lengths in mixed HTML+PHP code will often be blow out so that the generated source remains reabable.

Control Structures[edit]

These include if, for, while, switch, etc. Here is an example of an if statement, as it is the most complicated of the control structures:

<?php
if ((condition1) OR (condition2)) {
    action1();
} else if ((condition3) AND (condition4)) {
    action2();
} else
{
   // Use one true brace in control structures
   // when the block is longer than one line
    defaultAction();
    anotherAction();
}

// optional formatting if it improves readability
if ((condition1) OR (condition2)) {
    action1();
}
else if ((condition3) AND (condition4)) {
    action2();
}
else {
    defaultAction();
    anotherAction();
}

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

In layouts, the alternative named notation should be used:

<?php
if ((condition1) OR (condition2)) :
    action1();
elseif ((condition3) AND (condition4)) :
    action2();
else :
    defaultAction();
    anotherAction();
endif;

foreach ($array as $element) :
    echo $element;
endforeach;

Logical operators in condition statements should use uppercase words (AND, OR, etc) rather than programmatic notation (&&, ||, etc).

With the exception of case statements, curly braces must always be included even though 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:
        doAction1();
        break;

    case 2:
        doAction2();
        break;

    default:
        doDefaultAction();
        break;
}

Use indenting and line-breaks rather than curly braces in the case statements to increase readability. There should be no space between the condition and the colon in the case statement.

Function Calls[edit]

Functions should be called with no spaces between the function name and the opening parenthesis, and no space between this and the first parameter; a space after the comma between each parameter (if they are present), and no space between the last parameter and the closing parenthesis, and the semicolon. Here's an example:

<?php
$var = foo($bar, $baz, $quux);

As displayed above, there should be space before and one space after the equals sign used to assign the return value of a function to a variable. In the case of a block of related assignments, tabs (not spaces) may be inserted to promote readability:

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

Function Definitions[edit]

Class and function declarations follow the "one true brace" convention:

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

class fooClass
{
    function fooMethod($arg1)
    {
        if ($arg) {
            $result = true;
        } else {
            $result = false;
        }
        return $result;
    }
}

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 OR !$dsninfo['phptype']) {
        return $this->raiseError();
    }

    return true;
}

Comments[edit]

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

See also Adding phpDocumentor comments

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

Including Code[edit]

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 PHP language statements, not functions. You don't need parentheses around the filename to be included.

PHP Code Tags[edit]

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

For files that contain only PHP code, the closing tag (?>) is never permitted. It is not required by PHP. Not including it prevents trailing whitespace from being accidentally injected into the output.

SQL Queries[edit]

SQL keywords are to be written in uppercase, while all other identifiers (which the exception of quoted text obviously) is to be in lowercase. Carriage returns should not be used as JDatabase::getQuery provides for formatted output. However, indenting with spaces to improve readability is desireable.

Queries should be wrapped in single quotes (as these text blocks are parsed faster by php).

All quoted string must using the Quote method to facilitate future compatibility with other database engines.

All table names should use the #_ prefix rather than jos_ to access Joomla! contents and allow for the user defined database prefix to be applied.

All expected integer or floating-point variable must be cast with (int), (float) or (double) as appropriate.

$state = 1;
$name  = 'bill';
$db    = &JFactory::getDBO();
$query = 'SELECT COUNT( c.id ) AS num_articles, u.id, u.username'.
    ' FROM #__content AS c'.
    ' LEFT JOIN #__users AS u ON u.id = c.created_by'.
    ' WHERE c.state = '.(int) $state
    '  AND u.id IS NOT NULL'.
    '  AND u.username <> '.$db->Quote( $name ).
    ' GROUP BY u.id'.
    '  HAVING COUNT( c.id ) > 0';
$db->setQuery();
// Output formated query:
if ($debug) {
    echo $db->getQuery();
}
$stats = $db->loadObjectList();

Comment Blocks[edit]

All source code files in the core PEAR distribution should contain the following comment block as the header:

<?php
/**
 * @version	$Id$
 * @package	Joomla
 * @copyright	Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
 * @license	GNU/GPL, see LICENSE.php
 */

Classes, functions, constants, class properties and class methods should all be supplied with appropriate DocBlocks.

/**
 * Short description for class
 *
 * Long description for class (if any)...
 *
 * @package    PackageName
 * @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 fooBar
{
    /**
     * @var int $id Primary key
     */
    public $id = null;
}

Please note that code contributed to the Joomla stack that will become the copyright of the project is not allowed to include @author tags. You should update the contribution log in CREDITS.php. Joomla's philosophy is that the code is written "all together" and there is no notion of any one person 'owning' any sectino of code.

Files included from third party sources must leave DocBlocks intact.

Example URLs

Naming Conventions[edit]

Classes[edit]

Classes should be given descriptive names. Avoid using abbreviations where possible. Class names should always begin with an uppercase letter and be written in CamelCase.

Third-party developers are advised to namespace their functions with a unique prefix.

Functions and Methods[edit]

Functions and methods should be named using the "studly caps" style (also referred to as "bumpy case" or "camel caps"). The initial letter of the name is lowercase, and each letter that starts a new "word" is capitalized. Some examples:

connect();
getData();
buildSomeWidget();

Private class members (meaning class members that are intented to be used only from within the same class in which they are declared; are preceded by a single underscore. For example:

class fooBar
{
    // Joomla 1.5 and earlier format
    var $_status = null;

    function _sort()
    {
    }

    // Joomla 1.6 format
    private $_status = null;

    protected function _sort()
    {
    }
}

Constants[edit]

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. For example, the constants used by the JError class all begin with "JERROR_".

Global Variables[edit]

If your package needs to define global variables, their name should start with a single underscore followed by the uppsercase class/package name and another underscore. For example, the JError class uses a global variable called $_JERROR_LEVELS.

With PHP5 and later you may use static class properties or constants instead of globals.

<?php
class JWhatever
{
    public static $instance = null;
    const SUCCESS = 1;
    const FAILURE = 0;
    // Methods...
}

Regular and Class Variables[edit]

Regular variables, follow the same conventions as function.

Class variables should be set to null or some other appropriate default value. Lining up the default values with tabs should only be used if particularly warranted for readability.

References[edit]

When using references, there should be a space before the reference operator and no space between it and the function or variable name. For example:

<?php
$ref1  = &$this->_sql;
$db    = &JFactory::getDBO();

Controllers[edit]

For single controller components, the naming convention is [Name]Controller.

<?php
/**
 * Content Controller
 * @package Joomla
 */
class ContentController extends JController
{
    // Methods
}
?>

The file name will generally be controller.php and is located in the component folder.

com_content
 / controller.php

For a multi-controller components, such as the Banners in the Administrator, the convention is [Component]Controller[Name].

<?php
/**
 * Banner Client Controller
 * @package Joomla
 */
class BannerControllerClient extends JController
{
    // Methods
}
?>

The files will be located in a /controllers/ folder under the component folder. The file names will reflect the name of the controller.

com_banner
  /controllers/
    / banner.php
    / client.php

Models[edit]

The naming convention is [Component]Model[Name].

<?php
/**
 * Banner Client Model
 * @package Joomla
 */
class BannerModelClient extends JModel
{
    // Methods
}
?>

The files will be located in a /models/ folder under the component folder. The file names will reflect the name of the model.

com_banner
  /models/
    / banner.php
    / client.php

Views[edit]

The naming convention is [Component]View[Name].

<?php
/**
 * Contact Category View
 * @package Joomla
 */
class ContactViewCategory extends JView
{
    // Methods
}
?>

The files will be located in a /view/ folder under the component folder. The subfolder names will reflect the name of a View.

com_contact
 /views/
   /view name 1/
     / view.html.php
   /view name 2/
     / view.html.php

Multi-view components such as com_content may provide an optional "master" view class the specialised views extend from. It is located in the component folder and typically called view.php. The naming convention is [Component]View.

com_content
 /views/
    /archive/
      / view.html.php
    /article/
 / view.php
view.php
<?php
/**
 * Content View
 * @package Joomla
 */
class ContentView extends JView
{
    // Helper Methods
}
?>

views/archive/view.html.php
<?php
/**
 * Content Archive View
 * @package Joomla
 */
class ContactViewArchive extends ContentView
{
    // Methods
}
?>

Layouts[edit]

Components may support different Layouts to render the data supplied by a View and its Models. A Layout file usually contains markup and some PHP code for display logic only: no functions, no classes.

A Layout consists of at least one .php file and an equally named .xml manifest file located in the /tmpl/ folder of a View, both reflect the internal name of the Layout. The standard Layout is called default.

com_content
  /views/
    /article/
      /tmpl/
        / default.php
        / default.xml
        / form.php
        / form.xml
        / pagebreak.php
        / pagebreak.xml 

The Layout may use supplemental .php files to provide more granual control in order to render individual parts or repetitive items of the data.

Users may customise the Layout output via Template Layout Overrides.

Templates[edit]

Template Layout Overrides[edit]