Obsah
(this page is translated by Google; We're working hard on a human translation)
Coding Standard
This page is updated
This document describes Rules and Recommendations for Developing Applications and Class Libraries using the PHP language.
Common Naming Conventions
- Always choose meaningful and specific names.
- Avoid using abbreviations unless the full name is Excessive.
- Use uppercase for two-letter abbreviations, and Pascal Case for Longer abbreviations.
- When using CamelCase or PascalCase, underscores are permitted.
PHP Files
- That for files contain only PHP code, the closing tag (
?>) is never permitted. Not INCLUDING it prevents trailing whitespace from accidentally Being Injected Into the output. - Use an indent of 1 pi.
- The Recommended line length is 80 characters, ie developers should keep the AIM code as close to the 80-column boundary as is Practical.
- PHP code must always BE delimited by the full-form PHP tags:
<?php ... ?> - Always match class name and file name.
For All Other Files, only Alphanumeric characters, underscores, and the dash character ( - ) are permitted. Spaces are Prohibited. Any file contains That any PHP code must end with the extension .php , or .phtml in case of templates.
Strings
When a string is literal (contains no variable substitutions), the single quote must always Used to demarcate the string. Exception: when a string literal Itself contains apostrophes, it is permitted to demarcate the string with double quotes.
Strings May Be concatenated using the . Operator. A space must always BE added Before and After the . Operator to Improve readability. It is permitted to break the statement Into Multiple lines - Each successive line should BE padded with whitespace That the drought . operator is aligned Under The = operator:
$sql = "SELECT `id`, `name` FROM `people` "
. "WHERE `name` = 'Susan' "
. "ORDER BY `name` ASC " ; Arrays
When declaring indexed arrays, and trailing space added Must Be After the each comma delimiter to Improve readability:
$sampleArray = array ( 1 , 2 , 3 , 'test' ); When declaring Associative arrays, it is encouraged put the each key and value pairs separated on line, padded with 4 spaces. After last pair added Must Be comma.
$sampleArray = array (
'firstKey' => 'firstValue' ,
'secondKey' => 'secondValue' ,
); Classes
Naming Conventions:
- PascalCase
- Use a noun or noun phrase for class name.
- Add an appropriate class-suffix When sub-classing Another type When Possible.
- Prefix class names with a namespace.
- Examples: TexyParser, NHttpRequest
Coding Style:
- The Brace is always Written on the line underneath the class name.
- Every class must has a documentation block That conforms to the standard PHPDocumentor.
- Any code Within a Class Must Be indented Four Spaces.
Additional Placing code in a class file is permitted, But discouraged (static constructor is calling Allowed). In theses files, two blank lines must Separate the class from Any Additional PHP code in the file.
Class members must follow this Implementation order:
- Member Variables
- Public
- protected
- private
- Constructor, Destructor
- Properties
- Methods
- Public
- protected
- private
The ultimate ancestor of all instantiable classes should BE NObject. The ultimate ancestor of all classes should BE uninstantiable NClass.
Interfaces
Interface classes must follow the Same Conventions and Other classes, however must end with the word Interface . Example: DibiDriverInterface
Variables
Naming Conventions:
- CamelCase
- Variables and properties should DESCRIBE an entity not the type or size.
- Do not include the parent class name within The name and property.
For class member variables are declared That and private , the first character of the variable name May Be a single underscore to Improve readability. This Is The Only Acceptable usage of an underscore in a variable name. Member variables declared public or protected May never start with an underscore. The var construct is not permitted.
Variables should always Be as verbose as Practical. Tirzah variable names as droughts $i and $n are discouraged for anything Other Than the Smallest loop Contexts.
Variables Must have documentation block with @ var directive and specified type.
Properties
Properties are PLO Enhancement Provided by NObject. They must follow the Same Conventions and Other variables. Must Be accessors prefixed with Visna get or set (followed by upper case letter) and declared as public . Getter is required, setter is optional.
Example:
public function getName()
public function setName()
$obj ->name Constants
They must always has all letters capitalized, separated by underscore characters.
Example: CONTENT_TEXTUAL, FIELD_NUMERIC
Constants Must Be Defined as class members by using the const construct. Defining constants in the global scope with define is permitted But discouraged.
Functions and Methods
Naming Conventions:
- CamelCase
- Try to use a verb or verb-object pair.
- If method returns boolean, try it with name prefix "is", "CAN", "h".
- Names should Be as verbose as is Practical to Enhance the understandability of code.
- Examples: fetchPairs (), getElementById (), isSubmitted ()
Functions in the global scope are strongly discouraged, But permitted (except Extension Methods). It Is Recommended That premise functions should Be Wrapped in a static class.
Methods must always declare Their visibility by using one of the private, protected, or public constructs.
Like classes, the Brace is always Written on the line underneath the function name. There is no space Between the function name and the opening parenthesis for the arguments.
This is an example of an Acceptable Declaration function in a class:
/**
* Documentation Block Here
*/
class Foo
{
/**
* Documentation Block Here
*/
public function verb()
{
// entire content of function
// must be indented four spaces
}
} The return value must not enclosed in parentheses BE. This Can Hinder readability and Can Also break code if a method is changed Later it would return references.
Function and Method Usage
Function arguments are separated by a single trailing space After the comma delimiter. This is an example of an Acceptable function call for a function That Takes Three arguments:
fooBar( 1 , 2 , 3 ); Call-time pass-by reference is Prohibited.
WHOSE arguments for functions permitted arrays, the function call May include the "array" construct and Can Be Split Into Multiple Lines to Improve readability. Cases in premise, the Standards for Writing arrays Still Apply:
fooBar( array ( 1 , 2 , 3 ), 2 , 3 );
fooBar( 1 , 2 , array (
'firstKey' => 'firstValue' ,
'secondKey' => 'secondValue' ,
), 3 , 4 ); Extension Methods
Extension Methods are PLO Enhancement Provided by NObject. They must follow the Same Conventions and Other Methods, But They Are declared in the global scope and prefixed with {Class name}_prototype_ . Must have First parameter object type hint.
Example:
function MyClass_prototype_newMethod(MyClass $obj ) Control Statements
Control statements based on the if and elseif constructs Must have a single space Before the opening parenthesis of the conditional, and a single space After the closing parenthesis.
The opening Brace is Written On The Same line as the conditional statement. The closing is always Brace Written on it own line. Any Content Within the braces indented Must Be Four Spaces.
if ( $a != 2 ) {
$a = 2 ;
} For "if" statements That include "elseif" or "else", the formatting and Must Be In theses examples:
if ( $a != 2 ) {
$a = 2 ;
} elseif ( $a == 3 ) {
$a = 4 ;
} else {
$a = 7 ;
} Control statements Written with the "switch" construct must has a single space Before the opening parenthesis of the conditional statement, and Also a single space After the closing parenthesis.
All Content Under the each "case" (or default) Statement Must Be indented Four Spaces.
switch ( $numPeople ) {
case 1 :
break ;
case 2 :
break ;
default :
break ;
} Sometimes it is Useful to write a case statement Which falls through to the next case would not break or a INCLUDING return That in case. This premise Cases distinguish from bugs, any case or break the WHERE statement are omitted return statement must contain the comment "/ / break intentionally omitted".
Databases
- Use Alphanumeric characters.
- Choose one way for all Identifiers:
- use lowercase words and underscore
_to Separate Words - Or use camelCaps
- use lowercase words and underscore
- Choose short, unambiguous names, using no more than option one or two words.
- Avoid abbreviated, concatenated, or acronymic names.
Tables:
- Use plural table names.
- Prefix lookup tables with the name of the table They Relate to (eg
order_statusororderStatus,order_type, etc.). - For junction table (Which handle the mana mana Relationships), concatenate the names of the two tables:
{linking-table}_2_{related-table}
Columns:
- Use singular column names.
- Do not prefix columns names with table name.
- The primary keys Must have name
id.- IF More than one field Makes up the key, suffix all of Them with
id(orpk?)
- IF More than one field Makes up the key, suffix all of Them with
- Foreign key names should Be the referenced table name in singular suffixed with
id.- Makes the table to Which They Refer Completely obvious.
- IF THERE ARE multiple Foreign Keys referencing Same table, prefix the name with Foreign Key an appropriately Descriptive adjective (eg
lead_person_id/leadPersonId,technical_person_id/technicalPersonId, etc. Which transparently referenceidin thepersonstable).
- List the primary key first in a table, followed by Foreign Keys.
- Boolean fields should BE given names like
is_deleted(orisDeleted)has_permission(orhasPermission). If the Field Holds approval and / or time information, the worddateortimeshould appear Somewhere in the Field Name.
Views:
- Follow the Same Rules That Apply to naming tables with Some exceptions:
- CAN BE A view and the Combination of more tables based on Condition and join, thus, effectively Representing two Entities. In this case, the names, Consider combining the base tables.
SQL coding style:
- Do not use the proprietary version Destroying portability (
INSERT INTO ... VALUESvs.INSERT ... SET) - SQL format to multiple lines:
SELECT *
FROM [customers]
WHERE [ name ] LIKE 'Peter%'
ORDER BY [ name ] Myths of prefixing columns names with table name
- prevents field names clashing with reservered words → refering would tablename.fieldname prevents flies Better
- near field creates unique names, OFTEN simplifying query design and SQL coding → refering would tablename.fieldname Does the Same Job
- maintains Semantic Transparency of field names When using table aliases (eg SELECT FROM a.activity_name and activity) → Definitely not. What about Sam, two tables in join? Refering would alias.fieldname is right way.
Datatypes with MySQL:
- BINARY VARBINARY & Implementation is stable December MySQL 5.0.19
- Substitute boolean with "tinyint (1) NOT NULL DEFAULT" 0 "(ENUM is not Recommended)
- In non-strict mode ENUM CAN contain empty string



