Last updated April 10, 2014. Created by beeradb on July 28, 2002.
Edited by YesCT, pwolanin, xjm, LeeHunter. Log in to edit this page.

Note: The Drupal Coding Standards apply to code within Drupal and its contributed modules. This document is loosely based on the PEAR Coding standards. Comments and names should use US English spelling (e.g., "color" not "colour").

Drupal coding standards are version-independent and "always-current". All new code should follow the current standards, regardless of (core) version. Existing code in older versions may be updated, but doesn't necessarily have to be. Especially for larger code-bases (like Drupal core), updating the code of a previous version for the current standards may be too huge of a task. However, code in current versions should follow the current standards.

Note: Do not squeeze coding standards updates/clean-ups into otherwise unrelated patches. Only touch code lines that are actually relevant. To update existing code for the current standards, always create separate and dedicated issues and patches.

See the Helper modules section at the bottom of this page for information on modules that can review code for coding standards problems (and in some cases, even fix the problems).

Proposed changes to Drupal coding standards are first discussed in the Core issue queue.

Contents of this Page

# Indenting and Whitespace

Use an indent of 2 spaces, with no tabs.

Lines should have no trailing whitespace at the end.

Files should be formatted with \n as the line ending (Unix line endings), not \r\n (Windows line endings).

All text files should end in a single newline (\n). This avoids the verbose "\ No newline at end of file" patch warning and makes patches easier to read since it's clearer what is being changed when lines are added to the end of a file.

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

# Casting

Put a space between the (type) and the $variable in a cast: (int) $mynumber.

# Control Structures

Control structures include if, for, while, switch, etc. Here is a sample if statement, since it is the most complicated of them:

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

(Note: Don't use "else if" -- always use elseif.)

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

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. The opening curly should be on the same line as the opening statement, preceded by one space. The closing curly should be on a line by itself and indented to the same level as the opening statement.

For switch statements:

switch (condition) {
  case 1:
    action1;
    break;

  case 2:
    action2;
    break;

  default:
    defaultaction;
}

For do-while statements:

do {
  actions;
} while ($condition);
 

Alternate control statement syntax for templates

In templates, the alternate control statement syntax using : instead of brackets is allowed. Note that there should not be a space between the closing paren after the control keyword, and the colon, and HTML/PHP inside the control structure should be indented. For example:

<?php if (!empty($item)): ?>
  <p><?php print $item; ?></p>
<?php endif; ?>

<?php foreach ($items as $item): ?>
  <p><?php print $item; ?></p>
<?php endforeach; ?>

Line length and wrapping

The following rules apply to code. See Doxygen and comment formatting conventions for rules pertaining to comments.

  • In general, all lines of code should not be longer than 80 chars.
  • Lines containing longer function names, function/class definitions, variable declarations, etc are allowed to exceed 80 chars.
  • Control structure conditions may exceed 80 chars, if they are simple to read and understand:
      if ($something['with']['something']['else']['in']['here'] == mymodule_check_something($whatever['else'])) {
        ...
      }
      if (isset($something['what']['ever']) && $something['what']['ever'] > $infinite && user_access('galaxy')) {
        ...
      }
      // Non-obvious conditions of low complexity are also acceptable, but should
      // always be documented, explaining WHY a particular check is done.
      if (preg_match('@(/|\\)(\.\.|~)@', $target) && strpos($target_dir, $repository) !== 0) {
        return FALSE;
      }
  • Conditions should not be wrapped into multiple lines.
  • Control structure conditions should also NOT attempt to win the Most Compact Condition In Least Lines Of Code Award™:
      // DON'T DO THIS!
      if ((isset($key) && !empty($user->uid) && $key == $user->uid) || (isset($user->cache) ? $user->cache : '') == ip_address() || isset($value) && $value >= time())) {
        ...
      }

    Instead, it is recommended practice to split out and prepare the conditions separately, which also permits documenting the underlying reasons for the conditions:
      // Key is only valid if it matches the current user's ID, as otherwise other
      // users could access any user's things.
      $is_valid_user = (isset($key) && !empty($user->uid) && $key == $user->uid);

      // IP must match the cache to prevent session spoofing.
      $is_valid_cache = (isset($user->cache) ? $user->cache == ip_address() : FALSE);

      // Alternatively, if the request query parameter is in the future, then it
      // is always valid, because the galaxy will implode and collapse anyway.
      $is_valid_query = $is_valid_cache || (isset($value) && $value >= time());

      if ($is_valid_user || $is_valid_query) {
        ...
      }

    Note: This example is still a bit dense. Always consider and decide on your own whether people unfamiliar with your code will be able to make sense of the logic.

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

$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

function funstuff_system($field) {
  $system["description"] = t("This module inserts funny text into posts randomly.");
  return $system[$field];
}

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.

# Class Constructor Calls

When calling class constructors with no arguments, always include parentheses:

$foo = new MyClassName();

This is to maintain consistency with constructors that have arguments:
$foo = new MyClassName($arg1, $arg2);

Note that if the class name is a variable, the variable will be evaluated first to get the class name, and then the constructor will be called. Use the same syntax:
$bar = 'MyClassName';
$foo = new $bar();
$foo = new $bar($arg1, $arg2);

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

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

With that caveat in mind, single quote strings should be used by default. Their use is recommended except in two cases:

  1. Deliberate in-line variable interpolation, e.g. "<h2>$header</h2>".
  2. 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.

# 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

Comment standards are discussed on the separate Doxygen and comment formatting conventions page.

# 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 reasons for this can be summarized as:

  • Removing it eliminates the possibility for unwanted whitespace at the end of files which can cause "header already sent" errors, XHTML/XML validation issues, and other problems.
  • The closing delimiter at the end of a file is optional.
  • PHP.net itself removes the closing delimiter from the end of its files (example: prepend.inc), so this can be seen as a "best practice."

# 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 ?> -- NO

# Example URLs

Use "example.com" for all example URLs, per RFC 2606.

# Naming Conventions

Functions and variables

Functions and variables 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.

Persistent Variables

Persistent variables (variables/settings defined using Drupal's variable_get()/variable_set() functions) should be named using all lowercase letters, and words should be separated with an underscore. They should use 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 that defines them.
  • In Drupal 8 and later, constants should be defined using the const PHP language keyword (instead of define()), because it is better for performance:
    <?php
    /**
    * Indicates that the item should be removed at the next general cache wipe.
    */
    const CACHE_TEMPORARY = -1;
    ?>

    Note that const does not work with PHP expressions. define() should be used when defining a constant conditionally or with a non-literal value:

    <?php
    if (!defined('MAINTENANCE_MODE')) {
     
    define('MAINTENANCE_MODE', 'error');
    }
    ?>

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.

Classes

All standards related to classes and interfaces, including naming, are covered on http://drupal.org/node/608152 instead of here.

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.

# Helper Modules

There are several contributed modules/projects available to assist with review for coding standards compliance:

  • Coder module, which includes both Coder Review (reviews) and Coder Upgrade (updates your code). To use it:
    1. Install the module (like any other module)
    2. Click on the "Code Review" link in your navigation menu.
    3. Scroll down to "Select Specific Modules".
    4. Select the module you wish to review, and click the "Submit" button.

    As an alternative to starting from the Code Review link in navigation, you can also review a particular module's code by clicking on the link on the Modules admin screen.

  • Dreditor (a browser plug-in for reviewing patches and more)
  • PARevview (a set of scripts for reviewing project applications, which runs some coding tests)
  • Coder Sniffer (runs coding standards validation without loading drupal)
  • The Grammar Parser module provides an automated way of rewriting code files in compliance with code standards. You'll probably also need the Grammar Parser UI module.

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

In the Naming Conventions, in the File names section there is mentioned how documentation file names should be formatted but no word on the naming conventions for php, css, js files.

--author="jax "

also conventions for .tpl.php should be listed there in case there are any (see this related post)

and class files

I think this page (under "Comments") should have a sentence such as:

Drupal modules should follow the "Module documentation guidelines".

drupalshrek
Maintainer of the Flipcard module visible in use at the website to learn French and learn Thai

Line wraps are not mentioned anywhere. Even if they are never to be used (as I assume), they need to be mentioned as such.

Erik Webb
Technical Team Lead, Acquia

Agree they need to be mentioned. My 2 cents are hard-wrap at 80 characters, but that's my preference. I did notice a mention of this in docs at http://drupal.org/node/161085, but I assume that's just for docs, not code.

Joseph Cheek
@cheekdotcom / www.cheek.com

I've recorded over 1100 focused Drupal video tutorials at BuildAModule.

Here is a presentation I made on the same. Hope it helps some one.
Drupal coding standards in 10 minutes

Under the operators section it mentions that white spaces should be added before and after, is there a limit to the white space before?

For example I like to align any consecutive assignments for readability, this introduces extra white spaces and it fails the code sniffer test.

// This may not come out as expected here, but the ideas is it should line up.
$foo     = '4';
$foobar  = '7';
$foob    = '2';

I have added a check to my codesniffer code to allow for extra white spaces... (SpaceOperatorSniff.php)

public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();
// Check if there is at least one space there may be more
if(ltrim($tokens[($stackPtr - 1)]['content']) != $tokens[($stackPtr - 1)]['content']) {
$whitespace = true;
}
        if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE
            || $tokens[($stackPtr + 1)]['content'] != ' '
        ) {
            $error = 'A opeator statement must be followed by a single space';
            $phpcsFile->addError($error, $stackPtr);
        }
        if ($tokens[($stackPtr - 1)]['code'] !== T_WHITESPACE
            || !$whitespace
        ) {
            $error = 'There must be a single space befora a opeator statement';
            $phpcsFile->addError($error, $stackPtr);
        }
    }//end process()

btw, I think it's a bad idea to align consecutive statements because once you introduce a variable with a name that is longer than the previous ones you have to re-align all the other lines as well which reduces the readability of the patch you create afterwards.

--author="jax "

Since there was more than one recent discussion on that in the project appications review queue: The rule defined in this article obviously causes some confusion.

While the article says

All text files should end in a single newline (\n). This avoids the verbose "\ No newline at end of file" patch warning and makes patches easier to read since it's clearer what is being changed when lines are added to the end of a file.

it obviously means that, at the end of any file, a blank line should exist. Actually a blank line, in UNIX text files, means two newlines:

First line\n
Second line\n
....
Last line\n
\n

So I urgently suggest clarification in the document. Many people consider "newline" as an ASCII symbol (\n) and not as a synonym for a blank line.

No. What the article says is exactly what it means - "All text files should end in a single newline (\n)." That does not mean TWO \n characters, it means one. The explanation given in the article makes it clear what why this is desired. When in doubt, look at all the core files and you will see without exception that they all end in exactly one \n. There should never be a blank line at the end of any file.

<tr>.

This should be discussed with the folks working on drupalcs module then. Since it throws errors otherwise. It leads to many confusion in the project applications queue atm (that's why I commented here ;))

(Much core code wouldn't pass hardly any current coding standard IMO, btw, so I would not really make it a role model... but however, there seems to be a big need of discussion on this.)

Edit: I have raised this here #1346946: Newlines at file endings. My only goal is an end of this confusion, so hopefully this will soon be clear.

I am getting confused whether I need to hit the enter key at the end of file or not. I set my text editors to show the newline characters and took screenshots.

EOF newline character

According to this, the last blank line does not contain a '\n' or 'line feed' character. This contradicts with doitDave's comment above. Do some editor append \n to end of the last line?

We can probably update that page ... but I believe the intention is that all files should end with "a blank line containing a single newline character".

In other words, files must end with "\n" ... and not with "} \n".

EDIT: I believe wrongly. :)

We can probably clarify that page ... but I the intention is that all files should have "only one sequential newline character at the end of the file".

In other words, files should *NOT* end with "\n" alone on the final line.

telling people the place to join the discussion:

join http://groups.drupal.org/coding-standards-and-best-practices

Thomas

Combining IT and arts to organize
http://it-arts.org

I'm a little confused about whether the class name should or should not have the module name as a prefix - I see that methods and properties in a class don't have the prefix, and on the OO coding standards page it mentions that an underscore should be avoided in a class name (so I shouldn't use dailyWriter_DAOFactory). In the end, I want to know if I should name my class DAOFactory or DailyWriterDAOFactory. I figure this is a good example, as lots of OO modules are bound to have a DAOFactory class.

I don't want to start a flame or discussion about single and double quotes however, single quotes are not faster then double quotes. What's written is currently incorrect. You shouldn't do such micro optimizations anyway.

Roy Simkes

I think what is mentioned in this page is true and single quotes are faster then double quotes because when you use single quotes, PHP doesn't use more processes to interpret what is inside the single quote. And in this page its just recommended as its suggested in many other resources.

Doubt is the father of invention..... Hubmesh | download converter

What you said might have been true on older releases of PHP but not anymore. There are even cases where double quotes are actually faster. While what is suggested is true logically, it's not in the practical life.

Here are the benchmarks, where you can see for yourself: http://phpbench.com/

Roy Simkes

Although i am not sure about comparing their speed, i think its not useful to talk about this because always there are different ideas about it and actually its not very important.

Doubt is the father of invention..... Hubmesh | download converter

You can check drupal code style on your project automatically with this module http://drupal.org/project/dcq for team development through git.

Why base Drupal off of Pear coding standards 'loosely' instead of following it. There are way too many PHP 'coding standards' already each with their own slightly minor changes making developers switch back and forth between IDE editor and template settings.

For example at work we adhere to the Zend framework PHP coding standards and best practices which seem to me much more readable then most using 4 spaces (Pear also uses 4 spaces) instead of 2 like Drupal. The ZF templates are not currently reflecting this but I have been able to edit the templates much more freely in Aptana.

http://framework.zend.com/manual/en/coding-standard.coding-style.html

No war between spaces vs tabs. But personally i like tabs, cause it is defined for indent perpose.
But when i see PSR-1, it uses 4 spaces, and here drupal uses 2 spaces.
I'm not sure why they all like spaces.
I insist on my choice, sorry. Only this rule i hate.

the choice of spaces over tabs is to show the code the same for each editor. When using tabs, according to user preferences it can show 2 spaces or 4 spaces or 8 spaces. Everyone will see it differently. Consider someone using emacs and another one using eclipse. They both will see the same indentation if you use spaces. This is pretty much the general reason for spaces. It really makes sense if you think this way, and you can always set the preferences of your favorite editor to put spaces instead of tabs when you press the tab button.

Roy Simkes

the choice of spaces over tabs is to show the code the same for each editor. When using tabs, according to user preferences it can show 2 spaces or 4 spaces or 8 spaces. Everyone will see it differently. Consider someone using emacs and another one using eclipse. They both will see the same indentation if you use spaces. This is pretty much the general reason for spaces. It really makes sense if you think this way, and you can always set the preferences of your favorite editor to put spaces instead of tabs when you press the tab button.

We want standardised files, not standardise display. There is no reason for everyone to 'see' it the same way. As long as files are saved in a standard format, people can configure their favourite editor to 'see' it the way they want; 'press' whichever key they want; and when to perform tab<->space conversion (on key press, on file load/save, on vcs checkin/checkout).

I think the 'real' reason to use spaces is for full support of all possible terminals and text editors, even if they have different interpretation of the tab character and without tab size/conversion settings. Consider these 3 interpretations of the tab character - 1. move right by x columns; 2. move right until column is multiple of y; 3. move right until next arbitrarily set tabstop (in most GUI Word Processor) - mix them up and you get a big mess.

On side note, tab<->spaces conversion on key press is infeasible for those who works on multiple projects with different coding standards. If you need to edit files on a 2-spaces project and a 3-spaces project AT THE SAME TIME, eg. writing integration of 2 projects, how do you configure your favourite editor to handle tabs? Most editors cannot have different settings per project/file. You need script/vcs do the conversion on load/save or checkin/checkout. Or you can manually type spaces for every line even when you want to indent a 100 lines block. Ouch!

Another reason I think is that once you start using tabs, unless everyone uses the same tab settings (which they of course don't), formatting can end up looking a complete mess. For example, imagine someone has been editing a module with their editor set to show 2 spaces for 1 tab. Now, for example, lines which to this user look like they are indented by 4 spaces can have the following 3 combinations:

  • 2 tabs => 4 spaces
  • 1 tab + 2 spaces (or 2 spaces + 1 tab) => 4 spaces
  • 1 space + 2 tabs (the first tab will only go to the first tab point) => 4 spaces
  • 2 spaces + 1 tab => 4 spaces
  • 3 spaces + 1 tab (going to the 4th char) => 4 spaces
  • 4 spaces

The user will see the file is beautifully laid out, with all the indentations looking great.

Now consider what this code appears like to a user who has the tabs set to (say) 4 spaces. Note that a tab does not simply add a certain number of spaces, but goes to the next tab point:

  • 2 tabs => 8 spaces
  • 1 tab + 2 spaces (or 2 spaces + 1 tab) => 6 spaces
  • 1 space + 2 tabs (the first tab will only go to the first tab point) => 8 spaces
  • 2 spaces + 1 tab => 8 spaces
  • 3 spaces + 1 tab (going to the 4th char) => 8 spaces
  • 4 spaces

So all those indents which were perfectly aligned in the first example, now show up with 4, 6, or 8 spaces!

You could make the rule that only tabs are used for indents, and that should work, but as shown above, you cannot just allow tabs.

drupalshrek
Maintainer of the Flipcard module visible in use at the website to learn French and learn Thai

1. modern editors all have a feature which could set tab to "2 spaces" width(so it won't make a line go so far away from line beginning ^ )
If you comment as /* tabwidth=2 spaces */, everyone know how to set them in their editor. cause you are facing programmer, not normal user.
So in above situation, you just set 1 tab as 2 spaces. I dont know why you insist on "tab is not spaces" and also insist on "tab is 4 spaces or 6 spaces or 8 spaces". If they doesn't work fine, just set it back according to the comment.

2. when think about use 4 spaces, you might also think about use 2 spaces or even 3 spaces. there's no such arguments on tab.

3. * according to the file size view point(though it is a very small xxx -- how to say it in english), 4 spaces use 4 bytes, but 1 tab only use 1 byte.

4. * 1 tab is following MVC style!!! 1 tab is internal view point on Model, and you could set it as 2 spaces width or 4 spaces width according to your choice, that is View point. But 4 spaces is not. (Certainly i know there is also some trick on make 4 spaces to be viewed as 2 spaces, that surprise me…Why you want 2 spaces, but use 4 spaces instead of it, and then make it to be viewed as 2 spaces? Is it still the same thing comparing to 1 tab, just only add a default view -- default 4 spaces style???)

VOTE AGAINST SPACES

Subscribed, these arguments do really make some points.

So, yarco, how with you "vote against spaces" do you deal with the situation that in practise it just doesn't work, as I describe above?

drupalshrek
Maintainer of the Flipcard module visible in use at the website to learn French and learn Thai

If i met a guy insist on his 4 spaces style, i won't change his mind; but please don't also change my mind.
Then i say:
oh, let's work together, you just only need to set tabwidth to 4 spaces.
Everything is ok now...

And next day i met a guy insist on his 2 spaces style. I also work with him tell him to set tabwidth to 2 spaces...

You see, yes, i can work with 4 spaces guy and 2 spaces guy.

Now, we go together.
4 spaces and tab and 2 spaces...
who vs who?
4 spaces vs 2 spaces. tabs just need a result.

I did an extension for chrome to set tab as 2 spaces/4spaces/8spaces on fly.
you can get it from: https://github.com/yarcowang/chrome-tabsize

So now browser also support set tabsize by your choice.

I am a PHP developer so this article little helped me to know more new concepts here.But Please add more good information that would help others in such good way.
stairs

\n = lf or Line Feed
\r\n = crlf or Carriage Return and Line Feed

Thomas

Combining IT and arts to organize
http://it-arts.org

Is possible use vim folding marks?

E.g.:

<?php
function func_name($args) {
//{{{
  // the function code here...
}
//}}}
Thanks
?>

I responded to a user instead of posting it as a new comment:

Is possible use vim folding marks?

E.g.:

<?php
function func_name($args) {
//{{{
  // the function code here...
}
//}}}
Thanks
?>

Shouldn't including files be done via module_load_include() or form_load_include()?

--
www.ztwistbooks.com. Math books that are actually fun.

I feel there should be an exception for TPLs where HTML structure needs to be easily read by the front-end developers. The use of spaces means they can't start new lines around inline elements or elements that may be CSS'd inline as it actually outputs a single space between markup. This has stumped our themers on several occasions when back-end developers handed code that started a tag and span elements on new lines messing up output.

Yes you can just not do line breaks when you have chains of inline elements but it makes things messier and you also can't account for block elements that may or may not be CSS'd into inline or inline-block displays.

~G

Given the current direction of Drupal which is more 'embracing' of the wider PHP ecosystem. Is it time for the Drupal coding standards to update more in line with common PHP practices to make code more friendly for PHP developers that also work with many non-Drupal frameworks and libraries?

I'm thinking of Drupal PHP conventions which are uncommon in most other PHP based projects; this is the small list I came up with, you may be able to think of others:

  • print() not echo()
  • Uppercased TRUE, FALSE, and NULL

Constants should always be all-uppercase, with underscores to separate words. (This includes pre-defined PHP constants like TRUE, FALSE, and NULL.)

With regards to TRUE, FALSE, and NULL is it right to refer to them as constants given they are case-insensitive? Constants in PHP are case-sensitive. Most PHP projects I'm aware of use lowercase for these keywords.

For PHP developers like myself a Drupal project often becomes a bit mixed in it's use of echo vs. print, simply because it's more common in general php to use echo. There are occasional cases where the return value of print is useful but generally echo is sufficient.

Is there any page here or elsewhere that gives a complete overview of a module directory structure? If not, would it be a useful addition? Something that defines where all the elements go (css, js, included modules, libs, demo content, etc).

In php tags chapter there is nothing about <?= printing tag. I assume Drupal is following PSR-1 in this case (we can use it). Please correct me if I'm wrong?

It does say "Always use <?php ?> to delimit PHP code". Even though <?= isn't specifically barred (it only mentions "the shorthand, <? ?>"), I've always interpreted that to mean that we should ... uh ... always use <?php ?> to delimit PHP code.

--Andy
Developing Drupal websites for Livelink New Media since 2008

The arrays section talks a lot about how arrays should be formatted, but not what notation is acceptable. Do we have a community policy on the short syntax for arrays? For example the following code meets all the guidelines laid out in the array section but uses the square brackets instead of array():

<?php
$form
['title'] = [
 
'#type' => 'textfield',
 
'#title' => t('Title'),
 
'#size' => 60,
 
'#maxlength' => 128,
 
'#description' => t('The title of your node.'),
];
?>

--Andy
Developing Drupal websites for Livelink New Media since 2008

I slowly move over to the "new" array syntax. Drupal is very array keyword flooded, so using the alternate syntax could really speed things up.

That syntax is only supported in PHP 5.4+. Not even Drupal 8 currently requires PHP 5.4, so you shouldn't use it in core at least and if you do it in contrib, you'd have to specifiy the php version dependency in your .info file. While nice, not really worth locking 5.3 users out IMHO.

This has since changed for 8.x. #1498574: [policy, no patch] Require PHP 5.4

you can actually avoid the single quote escaping issue by using (U+2019) instead of the ASCII single quote (' U+0027).

it also looks better :)

--
törzsmókus