User:Dfwlogics/sandbox

PHP Coding Standards:

Spaces, Linebreaks and Indentation

·        Use two spaces for indentation. Don't use tab literal characters.

·        Use Unix linebreaks ("\n"), not MSDOS ("\r\n") or OS9 ("\r").

·        Put a space after control keywords like if and for.

·        Put a space after commas in argument lists.

·        Put a space around operators like =, <, etc.

·        Don't put spaces after function names.

·        Parentheses should hug their contents.

·        Generally, prefer to wrap code at 80 columns.

Case and Capitalization

·        Name variables and functions using lowercase_with_underscores.

·        Name classes using UpperCamelCase.

·        Name methods and properties using lowerCamelCase.

·        Use uppercase for common acronyms like ID and HTML.

·        Name constants using UPPERCASE.

·        Write true, false and null in lowercase.

Comments

·        Do not use "#" (shell-style) comments.

·        Prefer "//" comments inside function and method bodies.

PHP Language Style

·        Use "" tag.

·        Prefer casts like (string) to casting functions like strval.

·        Prefer type checks like $v === null to type functions like is_null.

·        Avoid all crazy alternate forms of language constructs like "endwhile" and "<>".

·        Always put braces around conditional and loop blocks.

PHP Language Features

·        Use PHP as a programming language, not a templating language.

·        Avoid globals.

·        Avoid extract.

·        Avoid eval.

·        Avoid variable variables.

·        Prefer classes over functions.

·        Prefer class constants over defines.

·        Avoid naked class properties; instead, define accessors.

·        Use exceptions for error conditions.

·        Use type hints, use assert_instances_of for arrays holding objects.

Examples

if/else:

if ($some_variable > 3) {

// ...

} else if ($some_variable === null) {

// ...

} else {

// ...

}

You should always put braces around the body of an if clause, even if it is only one line long. Note spaces around operators and after control statements. Do not use the "endif" construct, and write "else if" as two words.

for:

for ($ii = 0; $ii < 10; $ii++) {

// ...

}

Prefer $ii, $jj, $kk, etc., as iterators, since they're easier to pick out visually and react better to "Find Next..." in editors.

foreach:

foreach ($map as $key => $value) {

// ...

}

switch:

switch ($value) {

case 1:

// ...

break;

case 2:

if ($flag) {

// ...

break;

}

break;

default:

// ...

break;

}

break statements should be indented to block level.

array literals:

$junk = array(

'nuts',

'bolts',

'refuse',

);

Use a trailing comma and put the closing parenthesis on a separate line so that diffs which add elements to the array affect only one line.

operators:

$a + $b;                // Put spaces around operators.

$omg.$lol;              // Exception: no spaces around string concatenation.

$arr[] = $element;      // Couple [] with the array when appending.

$obj = new Thing;     // Always use parens.

function/method calls:

// One line

eject($cargo);

// Multiline

AbstractFireFactoryFactoryEngine::promulgateConflagrationInstance(

$fuel,

$ignition_source);

function/method definitions:

function example_function($base_value, $additional_value) {

return $base_value + $additional_value;

}

class C {

public static function promulgateConflagrationInstance(

IFuel $fuel,

IgnitionSource $source) {

// ...

}

}

class:

class Dog extends Animal {

const CIRCLES_REQUIRED_TO_LIE_DOWN = 3;

private $favoriteFood = 'dirt';

public function getFavoriteFood {

return $this->favoriteFood;

}

}

DocBlocks
A DocBlock is a multi-line C-style comment used to document a block of code. It begins with  and has an asterisk at the start of each line. Here’s an example:

<?php

/**

* Calculates sum of squares of an array

*

* Loops over each element in the array, squares it, and adds it to

* total. Returns total.

*

* This function can also be implemented using array_reduce;

*

* @param array $arr

* @return int

* @throws Exception If element in array is not an integer

* /

function sumOfSquares($arr) {

$total = 0;

foreach ($arr as $val) {

if (!is_int($val)) {

throw new Exception("Element is not an integer!");

}

$total += $val * $val;

}

return $total;

}

DocBlocks consist of three sections: short description, long description, and tags. All three sections are optional.

The short description is a succinct description terminated by either a new-line or a period. PhpDoc’s parsing routines are smart; it will only end the short description if the period is at the end of a sentence.

The long description is where the bulk of the documentation goes; it can be multi-line and as long you wish.

Both the long and short descriptions may contain certain HTML elements for formatting. HTML tags that aren’t supported will be displayed as plain text. PhpDoc can generate the documentation in multiple formats, though, so the HTML tags aren’t necessarily rendered as they would in an HTML file; the actual formatting depends on the generated file format. If you need to display an HTML tag as text, use double brackets. For example:

>Hello, world!<>

* /

The tags section of a DocBlock contains any number of special tags denoted by the  symbol. The tags are used to specify additional information, such as the expected parameters and their type. Most tags must be on their own line, with the exception of certain tags which may be inline. Inline tags are surrounded with curly braces and may be in both the long and short description.

If you need to start a line with the  symbol but you don’t want it to be interpreted as a tag, you can escape it with a backslash.

PhpDoc will automatically recognize textual lists in the long and short descriptions and it will parse them. However, it won’t parse nested lists correctly. If you want to use nested lists, use the HTML tags. Here is an example to illustrate what I mean:



*   Item 1

*   

*     Item 1.1

*     Item 1.2

*   

*   Item 2

* 

* /

Packages
PhpDoc packages are used to group related code elements in the generated documentation. You can specify packages for files and classes and the documented code they contain will inherit the package from them. To specify a package, set the  tag in a file-level or class-level DocBlock (file-level and class-level DocBlocks will be discussed further is the following section). A package name may contain letters, numbers, dashes, underscores, and square brackets (“[” and “]”).

Here is an example of defining a file’s package:

<?php

/**

* This is a file-level DocBlock

*

* @package Some_Package

* /

If you have multiple levels of packages and sub-packages, you can define a sub-package with the  tag. Here is an example:

<?php

/**

* This is a class-level DocBlock

*

* @package   Some_Package

* @subpackage Other

* /

class SomeClass {

}

If a file or class doesn’t specify a package it will be set to the default package, “default”. You can specify a different package to be used by default when generating the documentation via the  command-line option.

What Can we Document?
Not all code elements can be documented with DocBlocks. Here is a list of code elements that may be documented:


 * Files
 * Classes
 * Functions and methods
 * Class properties
 * Global variables

All of these elements can use certain common tags, but each has tags that are specific to that element. I’ll go over a few of the elements and the tags normally used to document them.

Files
File-level DocBlocks are used to document the contents of a file. It is highly recommended to include a file-level DocBlock in every file you document, and in fact PhpDoc will display a warning if one is not found when generating documentation.

Most elements are documented by placing a DocBlock before the element, but files are an exception (since you can’t write anything before a file). File-level DocBlocks are placed on the first line of the file.

A file-level DocBlock usually contains the tags,  ,  , and. The  and   tags were discussed earlier. The  tag is used to specify a URL to an external license that covers your code. The tag must contain the URL to the license and optionally a title. The  tag is used to specify the author of the file. It must contain the author’s name and optionally an email address in angle brackets.

Unlike most elements, a file-level DocBlock must contain a  tag in order to be parsed properly.

Here is a complete example of a file-level DocBlock:



* /

Classes
A class-level DocBlock is placed before a class definition and should describe the meaning of the class. Like file-level DocBlocks, class-level DocBlocks usually contain the tags,  , and. Here is an example:

<?php

/**

* An example class

*

* The class is empty for the sake of this example.

*

* @package   MyProject

* @subpackage Common

* @author    Moshe Teutsch <moteutsch@gmail.com>

* /

class Example {

}

Functions and methods
Functions and methods are documented identically in PhpDoc. Functions and methods usually contain the  and   tags in their DocBlocks. The  tag is used to document the expected type of a parameter. It contains three sections: the parameter, the data type, and an optional description. The  tag is used to document the return type. It contains two sections: the data type and an optional description. In both tags, the data type can be either a valid PHP data type, a class name, or “mixed”. It can also contain multiple options separated by a pipe.

<?php

/**

* Finds and returns user by ID or username

*

* @param int|string $user Either an ID or a username

* @param PDO $pdo A valid PDO object

* @return User Returns User object or null if not found

* /

function getUser($user, PDO $pdo)

{

// ...

if ($isFound) {

return new User(...);

}

return null;

}