Actions

Difference between revisions of "Coding style and standards"

From Joomla! Documentation

(Added condensed version for layout files)
(PHP Code Tags)
Line 196: Line 196:
 
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.
 
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.
+
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 (see PHP manual on [http://au.php.net/basic-syntax.instruction-separation instruction separation]).
  
 
=== SQL Queries ===
 
=== SQL Queries ===

Revision as of 06:53, 5 June 2009

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.


Contents

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

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

Spelling

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

E_STRICT-compatible code

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

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. Use your judgement based on the nature of the line and readability.

Control Structures

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) || (condition2)) {
    action1();
} else if ((condition3) && (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) || (condition2)) {
    action1();
}
else if ((condition3) && (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

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

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

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.

Please note - commented code is not to be committed to trunk or release repositories.

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
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

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 (see PHP manual on instruction separation).

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 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();

Doc Blocks

All source code files in the core Joomla distribution must 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
 */

The @package in the header is not required for class-only files.

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
 * @subpackage SubPackageName
 * @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 JFooBar
{
    /**
     * @var int $id Primary key
     */
    public $id = null;
}

The following package names are to be used in the core stack:

  • Joomla.Administrator - all files that belong only to the administrator or backend application
  • Joomla.Installation - all files that belong to the installation application
  • Joomla.Plugin - all plugin files
  • Joomla.Site - all files that pertain only to the site or frontend application
  • Joomla.XML-RPC - all files that belong to the XML-RPC server application

The sub-package name will vary according to the extension type:

  • Components - the component folder, eg com_content
  • Modules - the module folder, eg mod_latest_news
  • Plugins - the folder.element, eg content.pagebreak
  • Templates - the template folder, eg rhuk_milkyway
  • Framework - nothing for top level files (such as factory.php), the first level folder or the first.second level folders as appropriate, eg utilities for joomla/utitilies/date.php, html.html for joomla/html/html/email.php

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.

Layout files do not need full DocBlocks. However, they do require and Id tag and direct access block as follows:

<?php /** $Id$ */ defined('_JEXEC') or die('Restricted access'); ?>

Naming Conventions

Classes

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 even if using tradationally uppercase acryonyms (such as XML, HTML). One exception is for Joomla framework classes which must begin with an uppercase 'J' with the next letter also being uppercase. For example:

  • JHtmlHelper
  • JXmlParser
  • JModel

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

Functions and Methods

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. Function in the Joomla framework must begin with a lowercase 'j'. Some examples:

connect();
getData();
buildSomeWidget();
jImport();
jDoSomething();

Private class members (meaning class members that are intended to be used only from within the same class in which they are declared; are preceded by a single underscore. Properties are to be written in underscore format (that is, logical words separated by underscores) and should be all lowercase. For example:

class JFooBar
{
    // Joomla 1.5 and earlier format
    var $_status = null;
 
    function _sort()
    {
    }
 
    // Joomla 1.6 format
    private $_status = null;
 
    protected $field_name = null;
 
    protected function _sort()
    {
    }
}

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 JError class all begin with "JERROR_".

Global Variables

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

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

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();

Language Keys

Except for the most common of words, such as "Yes", "No", "Show", "Hide" all language keys should be namespaced to reflect the type of string they represent. Always consider that if two extensions use the same key, the one loaded last will be the one that displays. Namespacing should generally relate to the extension displaying the text. For example:

<?php
echo JText::_('Weblink Link');
echo JText::_('Weblink Title');
echo JText::_('Weblink Description');
 
echo JText::_('Exception An error occurred while saving');
?>

TODO: Link to page with "common" strings that can be used for typical actions in components, such a "Save"

Where the same English word is used in two different locations, two different language keys should be used to allow for cases where the translation results in different words or phrases.

// A table column title
<th><?php echo JText::_('Weblink Column Title');?></th>
<th><?php echo JText::_('Weblink Column Link');?></th>
 
// In the form
<?php echo JText::_('Weblink Title');?><input name="title" />
<?php echo JText::_('Weblink Link');?><input name="link" />

Toolbar and Linkbar text should be prefixed Toolbar and Linkbar respectively.

The language keys should be written as naturally as possible with spaces, not underscores separating words. Long phrases can be condensed to reduce keys to a sensible length. For example, tooltips for an edit field can be written like this:

<?php echo JText::_('Weblink Title');?><input name="title" title="<?php echo JText::_('Weblink Title Desc');?>" />

The convention used should be governed by common sense, but must be consistent. In general consider how the language file will look with all keys sorted alphabetically. Prefixes should be used to group text within a common context (such as column headings). Suffixes should be used to group elements that logically go together (such as a field name and its description).

Phrases must never be assembled by string concatenation. Each phrase must be represented by a single language key, using sprintf as appropriate to replace dynamic words in the phrase. Where replacements are made, the word used should be as descriptive as possible and all-uppercase. This assists the translators to determine the context of the replacement.

<?php
// Not permitted
echo JText::_('Deleted ').$n.JText::_(' items');
 
// Permitted
echo JText::sprintf('Message Deleted NUMBER items', $n);
?>

The reference in the language file would look like this:

MESSAGE DELETED NUMBER ITEMS=Deleted %d Item(s)

If more than one dynamic string is used in a phrase, the printf markers should employ order placement as other languages might change the position of the strings. This is done via %[number]$[printf_type] as follows:

Left to right language:

PAGE X OF Y=Page %1$d of %2$d

Right to left language:

PAGE X OF Y=%2$d of %1$d egaP

Controllers

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

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

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

Plugins

The naming convention is [Folder]View[Element].

class ContentPluginPagebreak extends JPlugin
{
    // Methods
}
?>

Layouts

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

Template Layout Overrides