1. Naming rules
1. Summary of naming rules
1) Use meaningful names
# goodif ($currentYear > 2009) ...# badif($t > 2009) ...
2) In abbreviations, only capitalize the first letter
# goodfunction getHttpHost()#badfunction getHTTPHost()
2. Class naming
1) The class should be named in the singular form of the noun, the first letter is capitalized, and the case is mixed.
class SqlStatement { ... }
2) The class representing a group of things should use the plural form
class SqlStatements { ... }
3) The beginning of the type is easier to identify than the end of the
type. For a variable of a known type, it is easier to identify its name starting with the type than ending with the type.
class ErrorConnection extends Error {// ... }$arrCatids = array(1,2,3,4,5,6);$strCatids = ‘1,2,3,4,5,6’;
4) The default implementation class of the interface can start with Default
class DefaultSqlBuilder extends ISqlBuilder {//... }
3. Interface naming
The name of the interface should be a noun or adjective beginning with the letter "I"
interface ISqlEngine{} interface ISortable{}
4. Variable/Attribute Naming
1) The attribute name should start with a lowercase letter and adopt the camel case rule.
public $userAuth;
3) The names of constants must be all uppercase letters.
All letters are uppercase, separated by underscores between words
const SEARCH_GOOGLE = 1;const SEARCH_YAHOO = 2;
4) When naming a group of objects, use the plural form
public $books;
5) Boolean variables should not use negative names
# goodpublic $isFound;public $isEnough;# badpublic $isNotFound;public $isNotEnough;
6) In nested loops, use meaningful and rich names to name loop control variables
# goodfor($row = 0; $i < getRows();$row++) {for($col= 0;$j < getCols(); $col++) {// ...}}# badfor($i = 0; $i < getRows();$i++) {for($j= 0;$j < getCols(); $j++){// ...}}
7) The incoming variables are written in snake form, and the custom function variables are written in snake form
# Controller variable class UserController extends Controller{function postLogin(Request $request) {// Here is the snake-like writing $order_status = $request->input('order_status');}}# Custom function variable# The input here Variables are written in snake form function route_url($route, $params, $option_params){// ...}
5. Function Naming
No Pinyin Nomenclature
1) The name of the class function starts with a lowercase letter and adopts the camel case rule
function getCurrentYear()
2) Use verbs to name functions
# 动词表:add / edit / removebegin / endcreate / destroyfirst / last get / releaseget / setincrement / decrementput / getlock / unlock open / closemin / max old / new start / stopnext / previoussource / targetshow / hidesend / receivecut / pasteup / down# 系词表:is / has
function startDatabase()function getDatabaseStatus()
3) Function names can omit class or object names to avoid duplication
# goodclass Font {function getFamily();}# badclass Font {function getFontFamily();}
4) Singleton classes should return their unique value through a static function called getInstance()
class Toolkit {private static const toolkit = new Toolkit();public static function getInstance(){return toolkit;}}
2. File Format/ Skills
1. leave blank
Proper use of spaces can effectively improve the readability of the code
1) General rules for using spaces
-
Operator, there should be a space before and after the colon.
-
Comma, there must be a space after the semicolon
# good$bit = $bitStart + $bitEnd;case 'someStr' :mysqlConnection($config, $dbname);if($count > 9)#bad$bit=$bitStart+$bitEnd;case 'someStr':mysqlConnection($config,$dbname);if($count>9)
2) Logical units should be separated by blank lines
function drawCapture() {$chars = getChars(5);// imageCreate$img = imageCreate();// output imageoutputImage();}
2. Control process
1) The format of for, while, if statement is as follows
# forfor (init; condition; update) {// ... }# whilewhile (condition) {// ... }# ifif (condition) {// ... } else if (condition) {// ... } else {// ... }
2) Loop/conditional statements must be nested with'(',')'
# goodif ($i > 0) {$val ++;}for ($i = 0; $i < $size; $i++) {$val ++;}# bad for($i=0; $i<$size; $i++) $val ++;if($i > 0) $val ++;
3) Use temporary variables to avoid compound conditional statements
# good$itemValid = $itemMoney > 800 && $level > 3 && $valid > 0;if($itemValid && isReady()) {display();}# badif($itemMoney > 800 && $level > 3 && $valid > 0 && isReady()) {display();}
4) The Switches statement should use the following format, and each branch must be clearly commented
switch (condition) {case 0:// show somethingbreak;default:// this is some code}
3. Statement
1) Class/interface declaration order The order
of the statements in the class document.
1. Document/Comment 2. Class/Interface Statement 3. Constant 4. Static Variable Order: [public, protected, (default), private] 5. Instance Variable Order: [public, protected, (default), private] 6. Constructor __construct(); 7. Function function;
2) The declaration of variables should be at the beginning of the code block, not where they are used
public function method() {$value = 0;...for (...) {$value += $num;}}
4. Skills
Delete the end of the file?>
The typical tags of php files start with <?php and end with ?>. However, in Zend Framework, it is not recommended to add ?> at the end of the php file
because any characters other than <?php ?> will be output to the web page, while the ones in it will not. So not adding ?> at the end can prevent the PHP file from being output to the webpage by maliciously added characters.
Array key
In PHP, it is legal to use a string without single quotes as the array key name, but we don't want this - the key name should always be enclosed in single quotes to avoid confusion. Note that this is a string, Instead of using variables as key names
// wrong $foo = $assoc_array[blah];// correct $foo = $assoc_array['blah'];// wrong $foo = $assoc_array["$var"];// correct $foo = $assoc_array[ $var];
Don't use uninitialized variables
// wrong if ($forum) ... // correct if (isset($forum)) ... // correct if (isset($forum) && $forum == 5)
Avoid using in_array() on large arrays
Avoid using in_array() on large arrays, and avoid using this function on arrays containing more than 200 elements in the loop. in_array() consumes resources. For small arrays, the impact may be small, but in a Checking a large array in a loop may take several seconds. If you really need this feature, please use isset() to find the array element. In fact, you use the key name to query the key value. The call isset($array[$var])
will in_array($var, array_keys($array))
be much faster.
SQL script format
SQL code often becomes very long, and it will be difficult to read without a certain format specification. SQL code is generally written in the following format, with keywords:
$sql = 'SELECT *<-one tab->FROM ' . SOME_TABLE . '<-one tab->WHERE a = 1 <-two tabs->AND (b = 2 <-three tabs->OR b = 3)<-one tab->ORDER BY b';
Here is an example with tabs applied:
$sql = 'SELECT *FROM ' . SOME_TABLE . ' WHERE a = 1 AND (b = 2 OR b = 3)ORDER BY b';
Prohibit the use of variables starting with a single letter
$tKey, $tVal
5. Use of blank lines
-
There must be a blank line after <?php
-
There must be a blank line between the two functions.
-
If there are other statements before return, die, and exit, add a blank line
3. Documents and Notes
1. PHPDoc
PHPDoc is a PHP version of Javadoc. It is an official standard for commenting PHP code. It supports the generation of API documentation through external document generators like phpDocumentor, and it can also help some integrated development environments such as Zend Studio, NetBeans, ActiveState Komodo Edit and IDE and Aptana Studio to understand variable types and other ambiguities in weakly typed languages And provide improved code completion, type hints and debugging functions.
Reference address: http://zh.wikipedia.org/zh/PH...
2. Notes
Annotation class
/** * This is an introduction to a certain class */ class SomeClass{}
Annotate local variables
function someFunction(){var $result; //obtained result set var $searchResult; //obtained search result set // ...}
Annotation variable
/** @var name string */public $name
Annotation functions
Annotations should be marked in the following order
* @param* @return* @see
3. PHP document header comments
/** * File header description * * @author Mark ([email protected]) * @copyright Copyright (c) 2014-2016 sour-lemon team */
Framework commonly used naming
Controller method
getIndex() # list getCreate() # create postCreate() # save and create getEdit() # edit postEdit() # save edit postUpdate() # batch update postDelete() # delete to the recycle bin postDestroy() # delete completely
Appendices
Appendix A: Reference Documents
-
PHPBB coding standard
http://www.phpbbchina.com/wik... coding standard -
Typecho PHP coding standard
https://code.google.com/p/typ... -
Optimize PHP in the process of writing code
http://www.yeeyan.org/article...
Appendix B: PHPDoc Tag Reference
Online version address: http://manual.phpdoc.org/HTML...
@abstract Documents an abstract class, class variable or method.@access public, private or protected Documents access control for an element. @access private indicates that documentation of element be prevented.@author author name <author@email> Documents the author of the current element.@category Specify a category to organize the documented element’s package into@copyright name date Documents copyright information.@deprecated version Documents a method as deprecated.@example /path/to/example Documents the location of an external saved example file.@exception documents an exception thrown by a method — also see @throws.@global type $globalvarname Documents a global variable or its use in a function or method.@ignore Prevents the documentation of an element@internal private information for advanced developers@link URL@name global variable name Specifies an alias for a variable. For example, $GLOBALS[‘myvariable’] becomes $myvariable@magic phpDocumentor tags}-.@package name of a package Documents a group of related classes and functions.@param type [$varname] description @return type description This tag should not be used for constructors or methods defined with a void return type.@see Documents an association to another method or class.@since version Documents when a method was added to a class.@static Documents a static class or method@staticvar Documents a static variable’s use in a function or class@subpackage @throws Documents an exception thrown by a method.@todo Documents things that need to be done to the code at a later date.@var type a data type for a class variable@version Provides the version number of a class or method.
Appendix C: Version changes
v1.4 (October 07, 2016)
Change to markdown format, and replace it with Laravel encoding format
V1.3 (April 19, 2015)
Project file structure description
V1.2 (April 27, 2013)
Separation of public parts of the project
V1.1 (April 2, 2013)
Add left formatted content
Add delete ?>
mark
V1.0 (November 7, 2012)
Initialization specification