- 9
- A
- A Block
- A Cold Day
- A Sync
- A cloudy day
- A3 Atlantis
- AD Blueprint
- AD Lemon Twist
- AD Novus
- AD Novus Fluid
- AD Redoable
- AD The Morning After
- ADT Basetheme
- AT Admin
- AT Koda
- AT Subtheme
- Aardvark
- Abac
- Abaca
- Abarre
- Aberdeen
- Aberdeen-liquid
- Abessive
- Ability
- About
- Aboutpeople
- Absolution
- Abstract
- Absynthe
- Abundant
- Acquia Marina
- Acquia Prosper
- Acquia Slate
- Acrylic
- Active NRebuild
- Activesite
- AdaptiveTheme
- Adaptivetheme Mobile
- Addari
- Aeon5
- Affaires
- Agregado
- Agua
- Airy Blue
- Alagna
- Alek 2.0
- Alina
- Alpha
- Amadou
- Amity Island
- Amor Azul
- Analytic
- Andreas 00
- Andreas
- Andreas00
- Andreas01
- Andreas02
- Andreas03
- Andreas04
- Andreas05
- Andreas06
- Andreas07
- Andreas08
- Andreas1024px
- Anita Kravitz
- Antique Modern
- Appleweb
- Aqua Fish
- Aquanaut
- Arclite
- Art School
- Arthemia
- Artists C01
- Artsy
- Aurora
- Aurora Australis
- Austere
- Austin
- Autumn Almanac
- aBeesParadise
- art4 green
- async
- awesome
- B
- B7
- Barlow
- Barron
- Barroness
- Basic
- Beach
- Beginning
- BeginningW2
- Berylizer
- Black Mamba
- Blackout
- BlogBuzz
- Blommor01
- Blossom
- Blue Bars
- Blue Citron
- Blue Lake
- Blue Nile
- Blue Zinfandel
- BlueTrip
- Bluefun
- Bluemarine
- Bluemarine ETS
- Blueprint
- Bluespan
- Bookstore
- Box_grey
- Burnt
- Burnt Rubber
- beMiracle Browny
- beat
- blix
- bluebreeze
- bluebreeze fixed
- box_cleanslate
- C
- Bisque
- Black
- Blue
- Brown
- CDMUG
- CTI Flex
- CWS
- Camaxtli
- Camsel
- Candy Corn
- Canvas
- Celju
- Chai Garam
- Chameleon
- Channel Nine
- Charity
- Chartreuse
- Cherry Blossom
- Christmas
- Chrono
- Chrysalis
- Clean
- Clean A
- Cleanfolio
- Cleanr
- Cleanstate - Liquid
- Cleanstate
- Clearblue
- Clearlooks
- Color Paper
- Color Paper Green
- Color Paper Orange
- Color Paper Pink
- Color Paper Purple
- Color Paper Super
- Colorart
- Colorfulness
- Colourise
- Combustion
- Contented7
- Contrast
- Coolweb
- Cornflower Blue
- CristalX4Drupal
- Deep Sky Blue
- Navy
- Orange Red
- Red
- Rhododendron Pink
- Turtle
- White
- changeme
- clear_dark
- coolwater
- D
- Drupal
- E
- F
- G
- GBIF
- Gainsboro
- Gardening
- Garfirst
- Garfish
- Garland
- Garland Accessible
- Genesis
- Genesis DARK
- Genesis LITE
- Genesis SUBTHEME
- Genesis Typo 1
- Genesis WebX
- Genesis Webify
- Genesis Zine
- German Newspaper
- Giordani
- GlossyBlue
- Gnifetti
- Golden Hour
- Goldfish
- Goofy
- Grass
- Grassland
- Green House
- Green'n'Black
- Greeny_Blu
- Gulmohar
- greens
- H
- I
- J
- K
- L
- M
- N
- O
- P
- Q
- R
- S
- Salamander
- Salamander Skins
- SanQ
- SanQReaL
- Sandium
- Sandtiger
- Sapo
- Scaccarium
- Scratch
- Scruffy
- Sea Breeze
- Seven
- Shallow Grunge
- Sharepoint-like
- Simpla - Liquid
- Simpla
- Simple Blog
- Simpler
- Simplex2
- Simply Green
- Simply Modern
- Sky
- Skyliner
- Skyroots
- Slash
- Slash black
- Slash blue
- Slash green
- Smooth Blue
- Social Networking Dream
- Solarflare
- Soldier
- Sports
- Spring Bloom
- Spring Theme
- Stark
- Starkish
- Stasis
- Strange Little Town
- Strix
- Summertime
- Sunny Sky
- Sunset
- SuperClean
- SynFox
- T
- The Big List
- U
- V
- Validators
- W
- X
- Y
- Z
Code standards
Submitted by peter on Thu, 11/05/2009 - 12:55
Drupal code standards are described in Coding standards. Most of them are good and common in the open source community. Some are just fashions inherited from the old days of Unix.
Drupal coding standards apply to anything loaded into drupal.org. When you download a theme or module from drupal.org, the code will comply with the Drupal standards. Some of the themes on this site comply with different standards, cannot be loaded into drupal.org, and are offered direct.
The Drupal standard is similar to the PEAR coding standard because the PEAR standards inherit many of the same standards adapted, where needed, for PHP.
Drupal uses the USA spelling for words, color
, and D-theme uses English, colour
, except when writing reserved words in HTML and CSS, where the American spelling is required.
The standards cover the following areas. The Drupal standard is described along with other standards you might see in D-theme and elsewhere.
- Indenting
- Whitespace
- Operators
- Control structures
- Function calls
- Function declarations
- Arrays
- Quotes
- String concatenations
- Comments
- Including code
- PHP code tags
- Semicolons
- CVS header
- Example URLs
- Naming conventions
Indenting
Drupal uses an indentation of 2 spaces for each level of indentation and tabs are not allowed. This is a style aimed at controlling presentation when writing code. The modern practice in editing, and an old practice in publishing, is to indent with tabs so the indentation can be varied when the result is presented. You can set your editing profile to display the indents at any width you require for easy reading on your screen then use a different spacing when printing. D-theme uses tabs and most publishers require tabs when you submit your book.
Whitespace
Drupal asks you to remove whitespace at the end of lines and it is a good idea because files are smaller plus you get less confusion when joining lines together. Whitespace can include all sorts of weird characters that do not display or display as spaces. Some editors display whitespace while others do not. If your editor does not display whitespace, get a new editor.
Drupal asks for files with lines ending in newline characters, entered into PHP string variables as \n. That is the modern style of line ending used in Linux, Unix, a recent Apple Mac operating system (which is just Unix with a botox treatment), and optional in Windows. Windows defaults to return newline, \r\n, which is the way display screens and printers used to work, and is used in Email because the email standards were written a long time ago. Older Apple operating systems, there were many, in fact there were many just on the Mac, \n\r, \r, and any other combination because they had no standard. Modern editors let you set the default for new files and convert existing files. Some FTP programs incorrectly assume you want to convert the line endings when copying files between operating systems and you have to switch off the conversion.
Operators
All binary operators (operators that come between two values), such as
+, -, =, !=, ==, >, etc. should have a space before and after the operator, for readability. For example, an assignment should be formatted as$foo = $bar;rather than$foo=$bar;. Unary operators (operators that operate on only one value), such as++, should not have a space between the operator and the variable or number they are operating on.
This is a good standard. Drupal used to have a more complex standard that was a fashion for a short while across many open source projects and is now disappearing.
Control structures
PHP control structures include if, for, while, switch, and are similar in Javascript. The first Drupal example is an if then else combination because it illustrates several conventions.
if (condition1 || condition2) {
action1;
}
elseif (condition3 && condition4) {
action2;
}
else {
defaultaction;
}This weird layout is common in Unix because it was used for unix then for Linux. A lot of teachers teach this style without knowing why. The following example shows a more modern style with improved readability and it is a style that was used a long time before people started writing Unix. This is the style used at D-theme because it leads to fewer mistakes when people modify code.
if (condition1 || condition2)
{
action1;
}
elseif (condition3 && condition4)
{
action2;
}
else
{
defaultaction;
}The modern style is called the Whitesmiths style because it is the style used in a Whitesmiths product released in 1977. I was taught the style by a person who learnt the style in the 1960s. The Unix style with the opening curly bracket, {, also called a brace, came along later to reduce the number of lines printed on very slow printers attached to Unix systems. There is no longer any reason to continue with the Unix style other than the fact that so many people do not know anything else.
Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls.
This is the Drupal standard despite that space being a presentation issue, not a code issue. Spaces are meaningless and the first high level language, Fortran, did not use spaces.
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.
A good standard and it should be compulsory, not just encouraged.
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.
$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:
$short = foo($bar);
$long_variable = foo($baz);Function declarations
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.
function funstuff_system($field) {
$system["description"] = t("This module inserts funny text into posts randomly.");
return $system[$field];
}The Drupal standard does not say anything about the return value. You should try to return the same type of value at all times. A function that returns a string should always return a string. When you need different values, use an object. You could write a function to return a string from value input and a null when the input is empty and false when the input is invalid but no, use an object. The object can then have methods to return true/false based on the presence or absence of data and the correctness of the data.
Arrays
Arrays should be formatted with a space separating each element (after the comma), and spaces around the => key association operator, if applicable:
$some_array = array('hello', 'world', 'foo' => 'bar');
Note that if the line declaring an array spans longer than 80 characters (often the case with form and menu declarations), each element should be broken into its own line, and indented one level:
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Title'),
'#size' => 60,
'#maxlength' => 128,
'#description' => t('The title of your node.'),
);Note the comma at the end of the last array element; This is not a typo! It helps prevent parsing errors if another element is placed at the end of the list later.
That trailing comma makes automated validation a problem. Trailing commas are not used on D-theme.
Quotes
Drupal does not have a hard standard for the use of single quotes vs. double quotes. Where possible, keep consistency within each module, and respect the personal style of other developers.
single quote strings are known to be faster because the parser doesn't have to look for in-line variables. Their use is recommended except in two cases:
- In-line variable usage, e.g. "<h2>$header</h2>".
- Translated strings where one can avoid escaping single quotes by enclosing the string in double quotes. One such string would be "He's a good person." It would be 'He\'s a good person.' with single quotes. Such escaping may not be handled properly by .pot file generators for text translation, and it's also somewhat awkward to read.
Hmm. Complicated. Single quoted strings do have to be scanned because they can contain escape characters and there is really not much difference in processing speed for most uses.
SQL is written with single quotes around string variables which makes double quotes the best choice around SQL.
HTML is written with double quotes around attribute values which makes single quotes the best choice around HTML. The HTML example, $x = "<h2>$header</h2>";, should be written as $x = '<h2>' . $header . '</h2>';. You can then easily write $x = '<h2 class="summary">' . $header . '</h2>';.
Javascript can use single or double quotes and might have both in the case where Javascript is generating HTML. Neither single nor double quotes can be specified as a standard for code that generates Javascript.
String Concatenations
Always use a space between the dot and the concatenated parts to improve readability.
<?php
$string = 'Foo' . $bar;
$string = $bar . 'foo';
$string = bar() . 'foo';
$string = 'foo' . 'bar';
?>When you concatenate simple variables, you can use double quotes and add the variable inside; otherwise, use single quotes.
<?php
$string = "Foo $bar";
?>When using the concatenating assignment operator ('.='), use a space on each side as with the assignment operator:
<?php
$string .= 'Foo';
$string .= $bar;
$string .= baz();
?>Comments
Inline documentation for source files should follow the Doxygen formatting conventions.
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.
Non-documentation comments should use capitalized sentences with punctuation. Sentences should be separated by single spaces. All caps are used in comments only when referencing constants, for example
TRUE. Comments should be on a separate line immediately before the code line or block they reference. For example:
// Unselect all other contact categories.
db_query('UPDATE {contact} SET selected = 0');If each line of a list needs a separate comment, the comments may be given on the same line and may be formatted to a uniform indent for readability.
C style comments (/* */) and standard C++ comments (//) are both fine. Use of Perl/shell style comments (#) 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: include_once() and require_once() are statements, not functions. You don't need parentheses around the file name to be included.
When including code from the same directory or a sub-directory, start the file path with ".":
include_once ./includes/mymodule_formatting.inc
In Drupal 7.x and later versions, use DRUPAL_ROOT:
require_once DRUPAL_ROOT . '/' . variable_get('cache_inc', 'includes/cache.inc');
PHP Code Tags
Always use <?php ?> to delimit PHP code, not the shorthand, <? ?>. This is required for Drupal compliance and is also the most portable way to include PHP code on differing operating systems and set-ups.
Note that as of Drupal 4.7, the
?> at the end of code files is purposely omitted. This includes for module and include files.
The Drupal standard gives a number of reasons for removing the trailing end tag. D-theme uses the trailing end tag because the files are HTML files with PHP inserted and the standard for script insertion is an element composed of matching start and end tags. Spaces after the end tag do not happen because the editor displays whitespace. If your editor does not display trailing whitespace, change editors.
Semicolons
The PHP language requires semicolons at the end of most lines, but allows them to be omitted at the end of code blocks. Drupal coding standards require them, even at the end of code blocks. In particular, for one-line PHP blocks:
<?php print $tax; ?> -- YES
<?php print $tax ?> -- NOCVS Header
All source code files in the core Drupal distribution should contain the following comment block in the header:
<?php
// $Id$This tag will be expanded by CVS to contain useful information
<?php
// $Id: CODING_STANDARDS.html,v 1.15 2008/12/22 15:27:26 keithsmith Exp $Example URLs
Use "example.com" for all example URLs, per RFC 2606.
Naming Conventions
Functions
Functions should be named using lowercase, and words should be separated with an underscore. Functions should in addition have the grouping/module name as a prefix, to avoid name collisions between modules.
Constants
Constants should always be all-uppercase, with underscores to separate words. This includes pre-defined PHP constants like TRUE, FALSE, and NULL. Module-defined constant names should also be prefixed by an uppercase spelling of the module they are defined by.
Never use uppercase. Never assign meaning to case because it is purely a presentation layer decoration that is, unfortunately, not understood by Unix or Linux. The result is domain names are correctly interpreted no matter what case you use but directory and page names fail on Unix and Linux if not typed in exactly the same case as they were created.
Do not use PHP constants. Pass settings around in objects. Using constants is equivalent to using a motorcar with airbags but not safety belts. The airbag hits your chest so hard that your heart stops. Using constants makes even less sense when you consider that most of the code using constants is already passing settings around in more focused ways.
Global Variables
If you need to define global variables, their name should start with a single underscore followed by the module/theme name and another underscore.
What a weird decision. Global variables are better than constants but use should be minimised and there should be a better standard. In the case of Drupal, there could be global variable versions of variable_get() and variable_set();.
Classes
Classes should be named using "CamelCase." For example:
<?php
abstract class DatabaseConnection extends PDO {
?>Ugh! Another use of case decoration to imply meaning. Use database_connection for readability. your documentation will mention the source of the code. (You do write documentation.)
Class methods and properties should use "lowerCamelCase":
<?php
public $lastStatement;
?>Ugh! Ugh!
The use of private class methods and properties should be avoided -- use protected instead, so that another class could extend your class and change the method if necessary. Protected (and public) methods and properties should not use an underscore prefix, as was common in PHP 4-era code.
private methods and properties are there for a reason. They indicate something internal that is not relevant to extending code. If public method a() uses private method b() then overriding a() makes b() irrelevant and you should replace all of a() without trying to reuse b(). In this example a() would be documented for public use but b() would not be documented.
File names
All documentation files should have the file name extension ".txt" to make viewing them on Windows systems easier. Also, the file names for such files should be all-caps (e.g. README.txt instead of readme.txt) while the extension itself is all-lowercase (i.e. txt instead of TXT).
Examples: README.txt, INSTALL.txt, TODO.txt, CHANGELOG.txt etc.
More ugh!. Case has no meaning. It might bring attention to a file. Using README.txt makes sense if it is the first file you should read. Using TODO.txt is senseless because it distracts attention away from README.txt. The best name for the first file is always_read_me_first.txt because it will appear near the top of the directory listing, except in operating systems that cannot present directory listings in alphabetical order.
Content block title
Content block body. This block shows you what a block looks like in the content region.
