2016-04-25 11:55:33 +02:00
# PHP Coding Conventions
2011-02-07 07:48:44 +01:00
This document provides guidelines for code formatting and documentation
to developers contributing to SilverStripe. It applies to all PHP files
2016-04-25 11:55:33 +02:00
in the `framework/` and `cms/` modules, as well as any supported additional modules.
2011-02-07 07:48:44 +01:00
Coding standards are an important aspect for every software project,
and facilitate collaboration by making code more consistent and readable.
If you are unsure about a specific standard, imitate existing SilverStripe code.
## File Formatting
### Indentation
Always use hard tabs rather then spaces for indentation, with one tab per nesting level.
### Maximum Line Length
2013-03-12 11:00:41 +01:00
The target line length is 100 columns with tabs being treated as four columns,
2016-04-25 11:55:33 +02:00
meaning developers should strive keep each line of their code
under 80 columns where possible and practical.
However, longer lines are acceptable in some circumstances.
2013-03-12 11:00:41 +01:00
The maximum length of any line of PHP code is 120 columns.
2011-02-07 07:48:44 +01:00
### Line Termination
2016-04-25 11:55:33 +02:00
Line termination follows the Unix text file convention. Lines must end with a single linefeed (LF) character.
2011-02-07 07:48:44 +01:00
Linefeed characters are represented as ordinal 10, or hexadecimal 0x0A.
2016-04-25 11:55:33 +02:00
Note: Do not use carriage returns (CR) as is the convention in Apple OS's (0x0D) or the carriage return -
2011-02-07 07:48:44 +01:00
linefeed combination (CRLF) as is standard for the Windows OS (0x0D, 0x0A).
## Naming Conventions
Class, function, variable and constant names may only contain alphanumeric characters and underscores.
### Classes
Class and filenames are in `UpperCamelCase` format:
:::php
class MyClass {}
2016-04-25 11:55:33 +02:00
If a class name is comprised of more than one word, the first letter of each
new word must be capitalized. Successive capitalized letters are used in
2013-03-12 11:00:41 +01:00
acronyms, e.g. a class `XMLImporter` is used while `XmlImporter` is not.
2011-02-07 07:48:44 +01:00
### Methods
Static methods should be in `lowercase_with_underscores()` format:
:::php
2012-01-30 23:13:42 +01:00
public static function my_static_method() {}
2011-02-07 07:48:44 +01:00
Action handlers on controllers should be in `completelylowercase()` format.
This is because they go into the controller URL in the same format (eg, `home/successfullyinstalled` ).
Method names are allowed to contain underscores here, in order to allow URL parts with dashes
(`mypage\my-action` gets translated to `my_action()` automatically).
:::php
2012-01-30 23:13:42 +01:00
public function mycontrolleraction() {}
2011-02-07 07:48:44 +01:00
Object methods that will be callable from templates should be in `$this->UpperCamelCase()` format.
Alternatively, `$this->getUpperCamelCase()` will work the same way in templates -
you can access both coding styles as `$UpperCamelCase` .
Other instance methods should be in `$this->lowerCamelCase()` format:
:::php
2012-01-30 23:13:42 +01:00
public function myInstanceMethod() {}
Methods inside classes must always declare their visibility by using one of the private, protected, or public modifiers.
2011-02-07 07:48:44 +01:00
### Variables
Static variables should be `self::$lowercase_with_underscores`
:::php
self::$my_static_variable = 'foo';
2012-01-30 23:13:42 +01:00
Member variables should be `$this->lowerCamelCase`
2011-02-07 07:48:44 +01:00
:::php
2012-01-30 23:13:42 +01:00
$this->myMemberVariable = 'foo';
Member variables always declare their visibility by using one of the private, protected, or public modifiers
2011-02-07 07:48:44 +01:00
### Constants
2016-04-25 11:55:33 +02:00
All letters used in a constant name must be capitalized,
2011-02-07 07:48:44 +01:00
while all words in a constant name must be separated by underscore characters.
:::php
2013-03-12 11:16:22 +01:00
const INTEREST_RATE = 0.19;
2016-04-25 11:55:33 +02:00
2011-02-07 07:48:44 +01:00
define('INTEREST_RATE', 0.19);
2016-04-25 11:55:33 +02:00
Constants must be defined as class members with the `const` modifier.
2011-02-07 07:48:44 +01:00
Defining constants in the global scope with the `define` function is permitted but strongly discouraged.
### File Naming and Directory Structure
Classes need to be in a file of the same name. Multiple classes are allowed to be contained in one file,
as long as the prefix of the class equals the filename, and is separated by an underscore from the remaining name.
For example `MyClass` and `MyClass_Controller` will both need to be placed into `MyClass.php` .
Example: `mysite/code/MyClass.php`
:::php
< ?php
2016-04-25 11:55:33 +02:00
2011-02-07 07:48:44 +01:00
class MyClass {}
2016-04-25 11:55:33 +02:00
2011-02-07 07:48:44 +01:00
class MyClass_Controller {}
2016-04-25 11:55:33 +02:00
2011-02-07 07:48:44 +01:00
class MyClass_OtherRelatedClass {}
2016-04-25 11:55:33 +02:00
To help with namespacing common class names (like Database) it is recommended to use a prefix convention `SS_ClassName` but the filename will remain `ClassName.php` .
2011-02-07 07:48:44 +01:00
2015-02-28 01:09:15 +01:00
See [directory structure ](directory_structure ) for more information.
2011-02-07 07:48:44 +01:00
## Coding Style
### PHP Code Declaration
PHP code must always be delimited by the full-form, standard PHP tags:
:::php
< ?php
Short tags are never allowed. For files containing only PHP code, the closing tag must always be omitted.
It is not required by PHP, and omitting it prevents the accidental injection of trailing white space into the response.
2013-03-12 11:00:41 +01:00
Files must end with an empty new line. This prevents problems arising from the end-of-file marker appearing where other
white space is expected.
2011-02-07 07:48:44 +01:00
### Strings
#### String Literals
When a string is literal (contains no variable substitutions), the apostrophe or "single quote" should always be used to demarcate the string:
:::php
$a = 'Example String';
#### String Literals Containing Apostrophes
2016-04-25 11:55:33 +02:00
When a literal string itself contains apostrophes, it is permitted to demarcate the string with quotation marks or "double quotes".
2011-02-07 07:48:44 +01:00
:::php
2015-03-07 13:32:04 +01:00
$greeting = "They said 'hello'";
2011-02-07 07:48:44 +01:00
This syntax is preferred over escaping apostrophes as it is much easier to read.
#### String Substitution
Variable substitution is permitted using either of these forms:
:::php
$greeting = "Hello $name, welcome back!";
$greeting = "Hello {$name}, welcome back!";
For consistency, placing the dollar sign outside of the brackets is not permitted:
:::php
$greeting = "Hello ${name}, welcome back!";
#### String Concatentation
Strings must be concatenated using the "." operator. A space must always be added before and after the "." operator to improve readability:
:::php
$copyright = 'SilverStripe Ltd (' . $year . ')';
2016-04-25 11:55:33 +02:00
When concatenating strings with the "." operator, it is encouraged to break the statement into multiple lines to improve readability.
2011-02-07 07:48:44 +01:00
In these cases, each successive line should be padded with white space such that the "."; operator is aligned under the "=" operator:
:::php
$sql = 'SELECT "ID", "Name" FROM "Person" '
. 'WHERE "Name" = \'Susan\' '
. 'ORDER BY "Name" ASC ';
### Arrays
#### Numerically Indexed Arrays
Negative numbers are not permitted as indices.
An indexed array may start with any non-negative number, however all base indices besides 0 are discouraged.
When declaring indexed arrays with the Array function, a trailing space must be added after each comma delimiter to improve readability:
:::php
$sampleArray = array(1, 2, 3, 'Zend', 'Studio');
2016-04-25 11:55:33 +02:00
It is permitted to declare multi-line indexed arrays using the "array" construct.
2011-02-07 07:48:44 +01:00
In this case, each successive line must be padded with spaces such that beginning of each line is aligned:
:::php
$sampleArray = array(1, 2, 3, 'Zend', 'Studio',
$a, $b, $c,
56.44, $d, 500);
2016-04-25 11:55:33 +02:00
Alternately, the initial array item may begin on the following line.
If so, it should be padded at one indentation level greater than the line containing the array declaration,
and all successive lines should have the same indentation;
2011-02-07 07:48:44 +01:00
the closing paren should be on a line by itself at the same indentation level as the line containing the array declaration:
:::php
$sampleArray = array(
1, 2, 3, 'Zend', 'Studio',
$a, $b, $c,
56.44, $d, 500,
);
2016-04-25 11:55:33 +02:00
When using this latter declaration, we encourage using a trailing comma for the last item in the array;
2011-02-07 07:48:44 +01:00
this minimizes the impact of adding new items on successive lines, and helps to ensure no parse errors occur due to a missing comma.
#### Associative Arrays
2016-04-25 11:55:33 +02:00
When declaring associative arrays with the `array` construct, breaking the statement into multiple lines is encouraged.
2011-02-07 07:48:44 +01:00
In this case, each successive line must be padded with white space such that both the keys and the values are aligned:
:::php
$sampleArray = array('firstKey' => 'firstValue',
'secondKey' => 'secondValue');
2016-04-25 11:55:33 +02:00
Alternately, the initial array item may begin on the following line.
If so, it should be padded at one indentation level greater than the line containing the array declaration,
and all successive lines should have the same indentation; the closing paren should be on a line by itself at the
same indentation level as the line containing the array declaration.
2011-02-07 07:48:44 +01:00
For readability, the various "=>" assignment operators should be padded such that they align.
:::php
$sampleArray = array(
'firstKey' => 'firstValue',
'secondKey' => 'secondValue',
);
### Function and Method Declaration
No method or function invocation is allowed to have spaces directly
before or after the opening parathesis, as well as no space before the closing parenthesis.
:::php
2012-01-30 23:13:42 +01:00
public function foo($arg1, $arg2) {} // good
public function foo ( $arg1, $arg2 ) {} // bad
2011-02-07 07:48:44 +01:00
2016-04-25 11:55:33 +02:00
Keep the opening brace on the same line as the statement.
2011-02-07 07:48:44 +01:00
:::php
// good
2012-01-30 23:13:42 +01:00
public function foo() {
2011-02-07 07:48:44 +01:00
// ...
}
// bad
2016-04-25 11:55:33 +02:00
public function bar()
2011-02-07 07:48:44 +01:00
{
// ...
}
2016-04-25 11:55:33 +02:00
In cases where the argument list exceeds the maximum line length, you may introduce line breaks.
Additional arguments to the function or method must be indented one additional level beyond the function or method declaration.
A line break should then occur before the closing argument paren,
which should then be placed on the same line as the opening brace of the function
or method with one space separating the two, and at the same indentation level as the function or method declaration.
2011-02-07 07:48:44 +01:00
:::php
public function bar($arg1, $arg2, $arg3,
$arg4, $arg5, $arg6
) {
// indented code
}
Function and method arguments should be separated by a single trailing space after the comma delimiter,
apart from the last argument.
### Control Structures
#### if/else/elseif
No control structure is allowed to have spaces directly
2013-03-12 11:17:15 +01:00
before or after the opening parenthesis, as well as no space before the closing parenthesis.
2011-02-07 07:48:44 +01:00
2016-04-25 11:55:33 +02:00
The opening brace and closing brace are written on the same line as the conditional statement.
2011-02-07 07:48:44 +01:00
Any content within the braces must be indented using a tab.
:::php
2013-03-12 11:16:22 +01:00
if($a != 2) {
2011-02-07 07:48:44 +01:00
$a = 2;
}
2016-04-25 11:55:33 +02:00
If the conditional statement causes the line length to exceed the maximum line length and has several clauses,
you may break the conditional into multiple lines. In such a case, break the line prior to a logic operator,
and pad the line such that it aligns under the first character of the conditional clause.
The closing paren in the conditional will then be placed on a line with the opening brace,
2011-02-07 07:48:44 +01:00
with one space separating the two, at an indentation level equivalent to the opening control statement.
:::php
2013-03-12 11:16:22 +01:00
if(($a == $b)
2011-02-07 07:48:44 +01:00
& & ($b == $c)
|| (Foo::CONST == $d)
) {
$a = $d;
}
2016-04-25 11:55:33 +02:00
The intention of this latter declaration format is to prevent issues when adding or removing clauses
from the conditional during later revisions. For `if` statements that include `elseif` or `else` ,
the formatting conventions are similar to the `if` construct.
2011-02-07 07:48:44 +01:00
The following examples demonstrate proper formatting for `if` statements with `else` and/or `elseif` constructs:
:::php
2013-03-12 11:16:22 +01:00
if($a != 2) {
2011-02-07 07:48:44 +01:00
$a = 2;
2013-03-12 11:16:22 +01:00
} elseif($a == 3) {
2011-02-07 07:48:44 +01:00
$a = 4;
} else {
$a = 7;
}
Statements with `if` can be written without braces on a single line as the block, as long as no `else` statement exists.
:::php
// good
if($a == $b) doThis();
2016-04-25 11:55:33 +02:00
2011-02-07 07:48:44 +01:00
// bad
if($a == $b) doThis();
else doThat();
2016-11-01 06:12:11 +01:00
#### Prefer identical (===) comparisons over equality (==)
Where possible, use type-strict identical comparisons instead of loosely typed equality comparisons.
Read more in the PHP documentation for [comparison operators ](http://php.net/manual/en/language.operators.comparison.php ) and [object comparison ](http://php.net/manual/en/language.oop5.object-comparison.php ).
:::php
// good - only need to cast to (int) if $a might not already be an int
if((int)$a === 100) doThis();
// bad
if($a == 100) doThis();
2011-02-07 07:48:44 +01:00
#### switch
2016-04-25 11:55:33 +02:00
All content within the "switch" statement must be indented using tabs.
2011-02-07 07:48:44 +01:00
Content under each "case" statement must be indented using an additional tab.
:::php
switch($numPeople) {
case 1:
break;
case 2:
break;
default:
break;
}
The construct `default` should never be omitted from a switch statement.
#### for/foreach/while
Loop constructs follow the same principles as "Control Structures: if/else/elseif".
### Separation of Logic and Presentation
Try to avoid using PHP's ability to mix HTML into the code.
:::php
// PHP code
2012-01-30 23:13:42 +01:00
public function getTitle() {
2016-04-25 11:55:33 +02:00
return "< h2 > Bad Example< / h2 > ";
2011-02-07 07:48:44 +01:00
}
2016-04-25 11:55:33 +02:00
2011-02-07 07:48:44 +01:00
// Template code
$Title
Better: Keep HTML in template files:
:::php
// PHP code
2012-01-30 23:13:42 +01:00
public function getTitle() {
2011-02-07 07:48:44 +01:00
return "Better Example";
}
2016-04-25 11:55:33 +02:00
2011-02-07 07:48:44 +01:00
// Template code
< h2 > $Title< / h2 >
## Comments
Use [phpdoc ](http://phpdoc.org/ ) syntax before each definition (see [tutorial ](http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_phpDocumentor.quickstart.pkg.html )
and [tag overview ](http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_tags.pkg.html )).
* All class definitions and PHP files should have `@package` and `@subpackage` .
* Methods should include at least `@param` and `@return` .
2016-04-25 11:55:33 +02:00
* Include a blank line after the description.
2011-02-07 07:48:44 +01:00
* Use `{@link MyOtherClass}` and `{@link MyOtherClass->otherMethod}` for inline references.
* Denote preformatted code examples in `<code></code>` blocks.
* Always start block-level comments containing phpdoc with two asterisks (`/** ... */`).
Example:
:::php
2016-04-25 11:55:33 +02:00
/**
2011-02-07 07:48:44 +01:00
* My short description for this class.
* My longer description with
* multiple lines and richer formatting.
2016-04-25 11:55:33 +02:00
*
2011-02-07 07:48:44 +01:00
* Usage:
* < code >
* $c = new MyClass();
* $c->myMethod();
* </ code >
2016-04-25 11:55:33 +02:00
*
2011-02-07 07:48:44 +01:00
* @package custom
*/
class MyClass extends Class {
2016-04-25 11:55:33 +02:00
2011-02-07 07:48:44 +01:00
/**
* My Method.
* This method returns something cool. {@link MyParentMethod} has other cool stuff in it.
2016-04-25 11:55:33 +02:00
*
2011-02-07 07:48:44 +01:00
* @param string $colour The colour of cool things that you want
2012-06-23 00:32:43 +02:00
* @return DataList A list of everything cool
2011-02-07 07:48:44 +01:00
*/
public function myMethod($foo) {}
2016-04-25 11:55:33 +02:00
2011-02-07 07:48:44 +01:00
}
2016-04-25 11:55:33 +02:00
2011-02-07 07:48:44 +01:00
### Class Member Ordering
Put code into the classes in the following order (where applicable).
* Static variables
2012-01-30 23:13:42 +01:00
* Member variables
2011-02-07 07:48:44 +01:00
* Static methods
* Data-model definition static variables. (`$db`, `$has_one` , `$many_many` , etc)
* Commonly used methods like `getCMSFields()`
* Accessor methods (`getMyField()` and `setMyField()` )
* Controller action methods
2013-04-26 11:48:59 +02:00
* Template data-access methods (methods that will be called by a `$MethodName` or `<% loop $MethodName %>` construct in a template somewhere)
2011-02-07 07:48:44 +01:00
* Object methods
### SQL Format
2016-04-25 11:55:33 +02:00
If you have to use raw SQL, make sure your code works across databases. Make sure you escape your queries like below,
2013-06-21 00:32:08 +02:00
with the column or table name escaped with double quotes as below.
:::php
MyClass::get()->where(array("\"Score\" > ?" => 50));
It is preferable to use parameterised queries whenever necessary to provide conditions
to a SQL query, where values placeholders are each replaced with a single unquoted question mark.
If it's absolutely necessary to use literal values in a query make sure that values
are single quoted.
2011-02-07 07:48:44 +01:00
:::php
2012-06-23 00:32:43 +02:00
MyClass::get()->where("\"Title\" = 'my title'");
2011-02-07 07:48:44 +01:00
Use [ANSI SQL ](http://en.wikipedia.org/wiki/SQL#Standardization ) format where possible.
2016-04-25 11:55:33 +02:00
### Secure Development
2011-02-07 07:48:44 +01:00
2016-01-14 11:59:53 +01:00
See [security ](/developer_guides/security ) for conventions related to handing security permissions.
2011-02-07 07:48:44 +01:00
## License
Parts of these coding conventions were adapted from [Zend Framework ](http://framework.zend.com/manual/en/coding-standard.overview.html ),
2012-03-24 22:16:59 +01:00
which are licensed under BSD (see [license ](http://framework.zend.com/license )).
2012-05-16 11:38:20 +02:00
## Related
2016-06-03 00:53:35 +02:00
* [JavaScript Coding Conventions ](/contributing/javascript_coding_conventions )
2015-02-28 01:09:15 +01:00
* [Reference: CMS Architecture ](/developer_guides/customising_the_admin_interface/cms_architecture )