View source for Coding Guidelines

{{toc numerate=1}}

===PHP Coding Standards===

%%(wacko wrapper=box)
**Development Directions**
  * Features
  * Performance
  * Reliability
  * Code simplicity
  * Standards conformance
  * Documentation
  * Pace of releases

**Packaging a Release**
  * Collect unapplied patches
  * Resolve outstanding issues
  * Regression testing
  * Enter beta
  * Resolve all bug reports
  * Final release
%%
<[Any fool can write code that a computer can understand. Good programmers write code that humans can understand. --- Martin Fowler, "Refactoring - Improving the design of existing code", p. 15]> 

====Introduction====
Coding Standards. Live them, love them.

Coding conventions are a set of guidelines for a specific programming language that recommend programming style, practices, and methods for each aspect of a program written in that language. These conventions usually cover file organization, indentation, comments, declarations, statements, white space, naming conventions, programming practices, programming principles, programming rules of thumb, architectural best practices, etc. 

Programming style, also known as code style, is a set of rules or guidelines used when writing the source code for a computer program. Following a particular programming style helps programmers read and understand source code conforming to the style, and to avoid introducing errors.

These are guidelines for software structural quality. Software programmers are highly recommended to follow these guidelines to help improve the readability of their source code and make software maintenance easier. 

Code conventions are important to programmers for a number of reasons:

  * 40%–80% of the lifetime cost of a piece of software goes to maintenance.
  * Hardly any software is maintained for its whole life by the original author.
  * Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
  * If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create.

====Comments====


=====Guidelines=====
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 acceptable.
  * Use of perl/shell style comments (## # ##) is prohibited except for debugging purposes.
    * e.g. ##  # Diag::dbg('GOLD', $parameter);##

Don't use ##@## in front of functions, this makes it much harder to debug. If you have to, a comment before it is required. [((https://www.php.net/manual/en/language.operators.errorcontrol.php 1))]

=====PHPdoc Tags=====
Inline documentation for classes should follow the PHPDoc convention, similar to Javadoc. More information about PHPDoc can be found here: 
  * https://www.phpdoc.org

=====File comments=====
Every file should start with a comment block describing its purpose and version message. The comment block should be a block comment in standard JavaDoc format. While all JavaDoc tags are allowed, only the tags in the examples below will be parsed by PHPdoc.

%%(hl xml)
/**
 *
 * brief description.
 * long description.  more long description.
 *
 */
%%

=====Function and Class Comments=====
Similarly, every function should have a block comment specifying name, parameters, return values, and last change date.
%%(hl xml)
/**
 * brief description.
 * long description.  more long description.
 *
 * @param     variable  description
 * @return    value     description
 * @uses MyClass::$items to retrieve the count from.
 * @deprecated use http->redirect() instead
 * @see
 *
 */
%%

=====Note=====
The placement of periods in the short and long descriptions is important to the PHPdoc parser. The first period always ends the short description. All future periods are part of the long description, ending with a blank comment line. The long comment is optional.

====Formatting===

=====Quotes=====
Understand ((https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single the difference between single and double quotes)). Use whichever is more appropriate.

=====Indenting=====
All indenting is done with TABS. Before committing any file to the repository, make sure you first replace spaces with tabs and verify the formatting.
Indentation should follow the logical structure of the code. Use real tabs not spaces.

=====Line endings=====
To have an agreement on the line endings is especially important if you use development environments on different operating systems.

Your platform’s default line ending may differ, source code written on Unix / Mac OS will use line feeds (LF), whereas Windows produce carriage returns AND line feeds (CRLF). 

!!Use **LF** not CRLF line endings.!!

=====PHP Tags=====
The use of  ##<?php## to delimit PHP code is required. This is the most portable way to include PHP code on differing operating systems and webserver setups. Also, XML parsers are confused by the shorthand syntax.

====Templating====


====Expressions====
  1. Use parentheses liberally to resolve ambiguity.
  1. Using parentheses can force an order of evaluation. This saves the time a reader may spend remembering precedence of operators.
  1. Don't sacrifice clarity for cleverness.
  1. Write conditional expressions so that they read naturally aloud.
  1. Sometimes eliminating a not operator (##!##) will make an expression more understandable.
  1. Keep each line simple.
  1. The ternary operator ##(x ? 1 : 2)## usually indicates too much code on one line. ##if... else if... else## is usually more readable.

====Functions====

=====Function Calls=====
Functions shall 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:
%%(hl php)
<?php
$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:
%%(hl php)
<?php
$short			= foo($bar);
$long_variable	= foo($baz);
%%

=====Function Definitions=====
Function declarations follow the unix convention and the ((https://en.wikipedia.org/wiki/Indent_style#Allman_style Allman indent style)) (Code folding reduces the cognitive load):
%%(hl php)
<?php

function foo_function($arg1, $arg2 = '')
{
  if (condition) 
  {
      statement;
  }

  return $val;
}
%%

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:
%%(hl php)
<?php

function connect(&$dsn, $persistent = false) 
{
  if (is_array($dsn)) 
  {
      $dsninfo = &$dsn;
  }
  else
  {
      $dsninfo = DB::parse_dns($dsn);
  }

  if (!$dsn_info || !$dsn_info['phptype'])
  {
      return $this->raise_error();
  }

  return true;
}
%%

====Objects====
Objects should generally be normalized similar to a database so they contain only the attributes that make sense.

Each object should have Error as the abstract parent object unless the object or its subclasses will never produce errors.

Each object should also have a ##create()## method which does the work of inserting a new row into the database table that this object represents.

An ##update()## method is also required for any objects that can be changed. Individual ##set()## methods are generally **not** a good idea as doing separate updates to each field in the database is a performance bottleneck.

##fetch_data()## and ##get_id()## are also standard in most objects. See the tracker code base for specific examples.

Common sense about performance should be used when designing objects.

====Naming====
<[snake_case or camelCase]>

  1. Constants should always be uppercase, with underscores to separate words. Prefix constant names with the name of the class/package they are used in. For example, the constants used by the DB:: package all begin with ##DB_##.
  1. ##true## and ##false## are built in to the php language and behave like constants, but should be written in **lowercase** to distinguish them from user-defined constants.
  1. Function names should suggest an action or verb: ##update_address##, ##make_state_selector##
  1. Variable names should suggest a property or noun: ##user_name##, ##width##
  1. Use pronounceable names. Common abbreviations are acceptable as long as they are used the same way throughout the project.
  1. Be consistent, use parallelism. If you are abbreviating “number” as “num”, always use that abbreviation. Don't switch to using “no” or “nmbr”.
  1. Use descriptive names for variables used globally, use short names for variables used locally.

%%(hl php)
<?php
$address_info = [...];

for($i = 0; $i < count($list); $i++)
%%

====Control Structures====
These include ##if##, ##for##, ##while##, ##switch##, etc. Here is an example if statement, since it is the most complicated form:
%%(hl php)
<?php

if ((condition1) || (condition2))
{
    action_1;
}
else if ((condition3) && (condition4))
{
    action_2;
}
else
{
    default_action;
}
%%
Control statements shall have one space between the control keyword and opening parenthesis, to distinguish them from function calls.

You should 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:
%%(hl php)
<?php

switch (condition)
{
    case 1: {
        action1;
        break;
    }
    case 2: {
        action2;
        break;
    }
    default: {
        default_action;
        break;
    }
}
%%

====Error Control Operators====
When  ((https://www.php.net/manual/en/language.operators.errorcontrol.php the @ operator)) is used, you have absolutely no idea where to start. If there are hundreds or even thousands of function calls with ##@## the error could be like everywhere. No reasonable debugging possible in this case. Moreover, it's better to add enough details to the error log, so developers are able to decide easily if a log entry is something that must be checked further or if it's just a 3rdparty failure that is out of the developer's scope.

You should know that there exists something like ##@##, but just **do not use it**. Many developers (especially those debugging code from others) will be very thankful.


====Including PHP Files====
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, which is preferred and use ##'## (apostrophes) **not** ##"## (quotes):
%%(hl php)
<?php

include 'pre.php';
%%

====Arrays====
The use of short array syntax is preferred.
%%(hl php)
<?php

$address_info = ['short', 'array', 'syntax'];
$person = [
	'first_name'		=> 'Wacko', 
	'surname'		=> 'Wiki'
];

%%

===Documentation===
...

===Task Tags===
  * DEPRECIATED
  * FIXME
  * TODO
  * XXX

===PHP Standards Recommendation (PSR)===
Fortunately for PHP developers, there is the PHP Standards Recommendation (PSR), comprised of the following five standards:

  ((https://www.php-fig.org/psr/psr-0/ PSR-0)): Autoloading Standard
  ((https://www.php-fig.org/psr/psr-1/ PSR-1)): Basic Coding Standard
  ((https://www.php-fig.org/psr/psr-2/ PSR-2)): Coding Style Guide
  ((https://www.php-fig.org/psr/psr-3/ PSR-3)): Logger Interface
  ((https://www.php-fig.org/psr/psr-4/ PSR-4)): Autoloader
  ((https://www.php-fig.org/psr/psr-12/ PSR-12)): Extended Coding Style

In some sense, it almost doesn’t matter what your coding standard is, as long as you agree on a standard and stick to it, but following the PSR is generally a good idea unless you have some compelling reason on your project to do otherwise. 

===See also ===

  1. http://php-coding-standard.de/php_coding_standard.php
  1. https://www.php.net/manual/en/language.types.string.php
  2. https://www.php.net/manual/en/tokens.php
  1. https://area51.phpbb.com/docs/31x/coding-guidelines.html
  1. http://codeigniter.com/user_guide/general/styleguide.html
  1. http://pear.php.net/manual/en/standards.php
  2. http://www.phptherightway.com