Difference between revisions of "Coding style and standards"

From Joomla! Documentation

m (→‎Controllers: formatting)
m (rollback and improve)
(54 intermediate revisions by 23 users not shown)
Line 1: Line 1:
{{review}}
+
{{archived|75794|cat=Development,Bug Squad|reason=
{{RightTOC}}
+
<h3>2013 Joomla! Coding standards repository</h3>
remark: The following information are copied from the old WIKI archive and not yet reviewed.
+
A new initiative moving the coding standards created for the Joomla Platform into a specific repository for the entire Joomla project. These standards will be applied to all Joomla coding, e.g. CMS, Framework, etc.
See: http://dev.joomla.org/component/option,com_jd-wiki/Itemid,/id,standards:coding/
+
<h3>Coding Standards as of December 2013</h3>
 
+
*[[gitio:coding-standards|Joomla Coding Standards]] are now located within the Joomla GitHub repository.
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.
+
<h4>See also</h4>
 
+
* [[Joomla_CodeSniffer|Codesniffers to check your style in php, Eclipse, NetBeans, PHPStorm, ..]]
== Coding Standards ==
+
* [https://github.com/joomla/coding-standards/tree/master/IDE Coding standards auto formatter settings for Eclipse, PHPStorm, Zend Studio]
 
+
The older document is kept here for historical reference.''
=== Indenting and Line Length ===
+
}}
 
 
Use tabs to indent, not spaces, with the tab-stops set to an equivalent of 4 spaces.
 
 
 
It is recommended that you break lines at approximately 75-85 characters. There is no standard rule for the best way to break a line, use your judgment and, when in doubt.
 
 
 
=== Control Structures ===
 
 
 
These include if, for, while, switch, etc. Here is an example if statement, since it is the most complicated of them:
 
 
 
<source lang="php">
 
<?php
 
if ((condition1) || (condition2)) {
 
    action1();
 
} elseif ((condition3) && (condition4)) {
 
    action2();
 
} else
 
{
 
  // Use one true brace in control structures
 
  // when the block is longer than one line
 
    defaultaction();
 
    anotheraction();
 
}
 
</source>
 
 
 
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:
 
 
 
<source lang="php">
 
<?php
 
switch (condition)
 
{
 
    case 1:
 
        action1;
 
        break;
 
 
 
    case 2:
 
        action2;
 
        break;
 
 
 
    default:
 
        defaultaction;
 
        break;
 
}
 
</source>
 
 
 
=== Function Calls ===
 
 
 
Functions should be called with no spaces between the function name and the opening parenthesis, one space for the first parameter; spaces between commas and each parameter, and one space between the last parameter, no space between the closing parenthesis, and the semicolon. Here's an example:
 
 
 
<source lang="php">
 
<?php
 
$var = foo( $bar, $baz, $quux );
 
</source>
 
 
 
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, tabs may be inserted to promote readability:
 
 
 
<source lang="php">
 
<?php
 
$short        = foo( $bar );
 
$long_variable = foo( $baz );
 
</source>
 
 
 
=== Function Definitions ===
 
 
 
Class and function declarations follow the "one true brace" convention:
 
 
 
<source lang="php">
 
<?php
 
function fooFunction( $arg1, $arg2 = '' )
 
{
 
    if (condition) {
 
        statement;
 
    }
 
    return $val;
 
}
 
 
 
class fooClass
 
{
 
    function fooMethod( $arg1 )
 
    {
 
        if ($arg) {
 
            $result = true;
 
        } else {
 
            $result = false;
 
        }
 
        return $result;
 
    }
 
}
 
</source>
 
 
 
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:
 
 
 
<source lang="php">
 
<?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;
 
}
 
</source>
 
 
 
=== Comments ===
 
 
 
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 (<tt>/* */</tt>) and standard C++ comments (<tt>//</tt>) are both fine. Use of Perl/shell style comments (<tt>#</tt>) is discouraged.
 
 
 
=== 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().
 
 
 
;Note: [[php:include_once|include_once]] and [[php:require_once|require_once]] are PHP ''language statements'', not functions. You don't need parentheses around the filename to be included.
 
 
 
=== PHP Code Tags ===
 
 
 
Always use <tt>&lt;?php ?></tt> to delimit PHP code, not the <tt>&lt;? ?></tt> 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 (<tt>?></tt>) is never permitted. It is not required by PHP. Not including it prevents trailing whitespace from being accidentally injected into the output.
 
 
 
=== SQL Queries ===
 
 
 
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 expected integer or floating-point variable must be [http://php.net/manual/language.types.type-juggling.php cast] with <tt>(int)</tt>, <tt>(float)</tt> or <tt>(double)</tt> as appropriate
 
 
 
<source lang="php">
 
$state = 1;
 
$name  = 'bill';
 
$db    = &JFactory::getDBO();
 
$query = 'SELECT COUNT( c.id ) AS num_articles, u.id, u.username'.
 
    ' FROM jos_content AS c'.
 
    ' LEFT JOIN jos_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();
 
</source>
 
 
 
=== Header Comment Blocks ===
 
 
 
All source code files in the core PEAR distribution should contain the following comment block as the header:
 
 
 
<source lang="php">
 
<?php
 
 
 
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
 
 
 
/**
 
* Short description for file
 
*
 
* Long description for file (if any)...
 
*
 
* PHP versions 4 and 5
 
*
 
* LICENSE: This source file is subject to version 3.0 of the PHP license
 
* that is available through the world-wide-web at the following URI:
 
* http://www.php.net/license/3_0.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_0.txt  PHP License 3.0
 
* @version    CVS: $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_0.txt  PHP License 3.0
 
* @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
 
{
 
}
 
 
 
</source>
 
 
 
 
 
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.
 
 
 
Files not in the Joomla! core repository should have a similar block stating the copyright, the license, and the authors. All files should include the modeline comments to encourage consistency.
 
 
 
Example URLs
 
 
 
Use "example.com", "example.org" and "example.net" for all example URLs and email addresses, per RFC 2606.
 
 
 
== Naming Conventions ==
 
 
 
=== Classes ===
 
 
 
Classes should be given descriptive names. Avoid using abbreviations where possible. Class names should always begin with an uppercase letter.
 
 
 
=== Functions and Methods ===
 
 
 
Functions and methods should be named using the "studly caps" style (also referred to as "bumpy case" or "camel caps"). Functions should in addition 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. Some examples:
 
 
 
<source lang="php">
 
connect()
 
getData()
 
buildSomeWidget()
 
XML_RPC_serializeData()
 
</source>
 
 
 
Private class members (meaning class members that are intented to be used only from within the same class in which they are declared; PHP4 does not support truly-enforceable private namespaces) are preceded by a single underscore. For example:
 
 
 
<source lang="php">
 
_sort()
 
_initTree()
 
$this->_status
 
</source>
 
 
 
=== 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. For example, the constants used by the DB:: package all begin with "DB_".
 
 
 
=== Global Variables ===
 
 
 
If your package needs to define global variables, their name 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.
 
 
 
=== Controllers ===
 
 
 
For single controller components, the naming convention is ''[Name]Controller''.
 
 
 
<source lang="php">
 
<?php
 
/**
 
* Content Controller
 
* @package Joomla
 
*/
 
class ContentController extends JController
 
{
 
    // Methods
 
}
 
?>
 
</source>
 
The file name will generally be ''controller.php'' and is located in the component folder.
 
<source lang="text">
 
com_content
 
/ controller.php
 
</source>
 
 
 
For a multi-controller components, such as the Banners in the Administrator, the convention is ''[Component]Controller[Name]''.
 
 
 
<source lang="php">
 
<?php
 
/**
 
* Banner Client Controller
 
* @package Joomla
 
*/
 
class BannerControllerClient extends JController
 
{
 
    // Methods
 
}
 
?>
 
</source>
 
 
 
The files will be located in a <tt>/controllers/</tt> folder under the component folder.  The file names will reflect the name of the controller.
 
<source lang="text">
 
com_banner
 
  /controllers/
 
    / banner.php
 
    / client.php
 
</source>
 
 
 
=== Models===
 
 
 
The naming convention is ''[Component]Model[Name]''.
 
 
 
<source lang="php">
 
<?php
 
/**
 
* Banner Client Model
 
* @package Joomla
 
*/
 
class BannerModelClient extends JModel
 
{
 
    // Methods
 
}
 
?>
 
</source>
 
 
 
The files will be located in a <tt>/models/</tt> folder under the component folder.  The file names will reflect the name of the model.
 
 
 
<source lang="text">
 
com_banner
 
  /models/
 
    / banner.php
 
    / client.php
 
</source>
 
 
 
=== Views ===
 
The naming convention is ''[Component]View[Name]''.
 
<source lang="php">
 
<?php
 
/**
 
* Contact Category View
 
* @package Joomla
 
*/
 
class ContactViewCategory extends JView
 
{
 
    // Methods
 
}
 
?>
 
</source>
 
The files will be located in a <tt>/view/</tt> folder under the component folder. The subfolder names will reflect the name of a View. Layout templates are located in the view's <tt>/tmpl/</tt> folder. The filenames reflect the name of a Layout.
 
<source lang="text">
 
com_contact
 
  /views/
 
    /view Name/
 
      /tmpl/
 
        / default.php
 
        / mylayout.php
 
    / view.html.php
 
</source>
 
Complex components using a large collection of Views and Layouts may provide an optional "master" view class. It is located in the component folder. The naming convention is ''[Component]View''.
 
<source lang="text">
 
com_content
 
  /views/
 
    /tmpl/
 
  / view.php
 
</source>
 
 
 
=== Layouts ===
 
 
 
=== Templates ===
 
 
 
=== Template Layout Overrides ===
 

Revision as of 23:11, 8 January 2014