An in depth discussion of the PHP coding specification

  • 2020-06-07 04:05:42
  • OfStack

Indent and white space characters (Indenting and Whitespace)
Use 2 Spaces instead of the tab key for code indentation (notepad++, Eclipse and other editors support this configuration);
There should be no white space at the end of a line
Use \n (Unix newline) instead of \r\n (Windows newline)
All documents should end with 1 blank line

Operator (Operators)
All 2 operators (operators between 2 values), such as +, -, =,! = = =, > Wait, leave a space at both ends of the operator, for example, $foo =$bar instead of $foo=$bar should be used.
All 1-element operators (operating on only one operator on duty), such as ++, should have no Spaces between values and operators

Transformation (Casting)
A space should be added between (type) and the variable to be transformed, such as (int) $mynumber.
Control structure (Control Structures)
The control structure includes if, for, while, switch, etc. Here is an example of a simple if statement structure:


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

(Note: Don't use "else if" -- always use elseif.)
Control statements should have a space between the keywords and the left parenthesis to distinguish them from function calls.
You should always use curly braces even if they are optional. This improves the readability of the code and reduces nesting of logic errors.
Example switch statement structure:

switch (condition) {
  case 1:
    action1;
    break;
  case 2:
    action2;
    break;
  default:
    defaultaction;
}
do-while  Example statement structure: 
do {
  actions;
} while ($condition);

Length and encapsulation (Line length and wrapping)
Typically, each line of code should be no more than 80 characters long
The line length can exceed 80 characters when the line contains an excessively long function name, function/class definition, variable declaration, and so on
For easy reading and understanding, the length of the control structure can exceed 80 characters

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

Control conditions (condition) should not be written in multiple lines
Control conditions should be broken down to make them easy to read and understand. Code should be written to avoid the following situations:

// DON'T DO THIS!
if ((isset($key) && !empty($user->uid) && $key == $user->uid) || (isset($user-
>cache) ? $user->cache : '') == ip_address() || isset($value) && $value >= time()))
{
  ...
}

Breaking up the control conditions is not only easy to read, but it's also easy to add comments to let you know why you're making this conditional judgment. Right

// 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) {
  ...
}

Function call (Function Calls)
When calling a function, there is no space between the name of the function and the left parenthesis. Except for the last parameter, each parameter should be followed by a space, such as:
$var = foo($bar, $baz, $quux);
As mentioned earlier, there should be one space on each side of the equal sign. When there are 1 series of related statements, the number of whitespace can be increased for readability, such as:
$short = foo($bar);
$long_variable = foo($baz);

Function declaration (Function Declarations)
Arguments that contain default values should be placed last, and when a function has a return value, try to return a value that is easy to understand:


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

Class constructor call (Class Constructor Calls)
Always include parentheses when calling a class constructor with no arguments
$foo = new MyClassName();

A class constructor with parameters
$foo = new MyClassName($arg1, $arg2);
If you use a variable as a class name, assign a value to the variable before calling the class constructor:


$bar = 'MyClassName';
$foo = new $bar();
$foo = new $bar($arg1, $arg2);

Array (Array)
The values of the array should be separated by Spaces, and the assignment operation symbol (= > ) The left and right sides should also contain Spaces:
$some_array = array('hello', 'world', 'foo' = > 'bar');
When the character length of the declared array exceeds 80 characters (usually when constructing forms and menus), the elements should be written in line and indented:

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

Note: There is a comma at the end of the last element of the array. This is not a hand error, but a parse error caused by missing commas when new elements are added to the end. (In some ways, adding a comma to the end of the last array element is a recommended practice, and even when submitting code to ES117en.org, some code specification detection scripts get a warning because the last element doesn't have a comma.)

Quotation marks (Quotes)
Drupal does not have a strong standard for single and double quotation marks, as long as it maintains unity 1 within the same module.
Using single quotes is more efficient than double quotes because the parser doesn't need to look for variables between quotes. Here are two ways to use double quotes:
There are variables in the quotes, like" < h2 > $header < /h2 > "
Use double quotes to avoid escaping "He's good person." You can use single quotes as well, but the.pot parser doesn't handle this very well, and it looks weird.

String concatenation (String Concatenations)
Spaces need to be added between the dot and the string to be concatenated for code readability:
If you simply concatenate variables, you can use double quotes
When using the connection assignment (.=), you need to reserve Spaces on either side of the symbol

Note (Comment)
The annotation specification is discussed separately on the Doxygen and the annotation format specification pages

Introduction code (Including Code)
require_once() for any unconditional reference to the file and include_once() for any conditional reference to the file. Both statements guarantee that the file is introduced only once.
When introducing code from the current directory or subdirectory, always start with a dot path
include_once ./includes/mymodule_formatting.inc
In Drupal 7 and later, the DRUPAL_ROOT constant is used:
require_once DRUPAL_ROOT . '/' . variable_get('cache_inc', 'includes/cache.inc');
PHP code tag (PHP Code Tags)
Always use a < ?php ? > To define the PHP code without using to < ? ? > . This is to comply with the Drupal specification and also to facilitate code references in other systems and platforms.
Starting from Drupal 4.7 and ending? > Are deliberately ignored for the following reasons:
Removing it avoids the occurrence of white space characters at the end of the file, which could cause the "file header sent (header already sent)" error, XHTML/XML validation error, and other problems
The PHP delimiter at the end of the PHP official note is optional
PHP. net itself also removes the delimiter at the end of the file (e.g. prepend. inc)

Semicolon (Semicolons)
The PHP language requires that most lines end with a semicolon, except for blocks of code. The Drupal code specification also requires this, and so does the block of code. Here is an example of a one-line block of code:
-- YES
-- NO
Example URL (Example URL)
Use ES222en. com to represent all examples URLs
Naming convention (Naming Conventions)
Functions and variables (Functions and Variables)
Function and variable names should be in lowercase, separated by an underscore. Functions should be prefixed with module groups/module names to avoid collisions between different modules.
Persistent variable (Persistent Variables)
A persistent variable is a variable obtained and set by the variable_get()/variable_set() function, whose name should be in lowercase and separated by an underscore between words. Persistent variables should also be prefixed with module groups/module names to avoid conflicts between different modules.

Constant (Constants)
Constants always require all uppercase letters, and words are separated by an underscore. (Including PHP built-in constants TRUE, FALSE, NULL)
Constants defined in a module should always be prefixed with the module name in uppercase.
After Drupal 8, you should use the const keyword instead of the define() function to define constants because it is more efficient
Note that const cannot be used with PHP expressions, so in conditional judgments and non-literals (ES257en-ES258en??) , you should still use the define() function

Global variable (Global Variables)
When you define a global variable, you should start with the module/topic name with an underscore
Class (Class)
The class name should be humped (that is, capitalized)

Methods (functions) and properties (member variables) in a class should use lowercase humps

When defining access rights, use protected instead of private so that other classes can extend and update methods as necessary. Protected and public functions and variables should not begin with an underscore.
More on object-oriented coding specifications
File name (Filename)
All documentation files should be suffixed with the.txt suffix for Windows users to view. Also, all file names should be in uppercase and file suffixes in lowercase.
For example, ES284en. txt, ES286en. txt, ES288en. txt, ES290en. txt and so on.

Auxiliary modules and tools
Coder module: You can follow some of the above code specifications to review and suggest changes to the code
Drupal Code Sniffer: Code specification detection tool
PAReview. sh: Also handles code specification detection scripts in sandboxes, following almost all of the above code specifications strictly and suggesting changes.


Related articles: