To improve work efficiency, ensure development effectiveness and rationality, and maximize the readability and reusability of program code, and improve communication efficiency, you need to edit a code specification. Why do we need to develop our own coding standards?
When we write code, a good coding specification can play a lot of undesirable effects for us. At least, it has the following benefits:
1. improve our coding efficiency. Uniform Code makes it easy for us to copy and paste it!
2. improve code readability.
3. show our major. When others see our code, they find that the entire code writing process is uniform, and the code is immediately pushed up!
4. facilitate team collaboration. Everyone uses the same specification, which eliminates the five-or eight-point writing mode and coordinates the same!
The code specification consists of two parts: code specification and Annotation specification.
In fact, the php script we wrote is actually composed of two major parts: writing code and commenting on the code! Different frameworks, or even different companies, may have different requirements for this. here we just make a summary of our writing specifications! Hope to inspire other friends
1. code writing specifications
Folder name:
The folder must contain lowercase letters. For example, to store the controller folder, name it controller.
File name:
If it is a class file, the names of the files should be the same and use the big hump. For example, Session. class. php, the corresponding class name is Session,
If it is a common tool script, it should be used in a uniform manner, such as common. php.
Class name:
Class names use the same big camper, Cookie class
Method name:
The function of this method is described in the form of verbs and rankings, such as sendMessage and SMS.
In object-oriented systems, the same rules are observed, but some rules are different:
public getUserName()protected _getTotalAmount()private _setBlanceAmount()
Variable naming rules:
We need to talk about the variables:
1. whether in object-oriented or non-object-oriented syntax, variables use a small hump, for example, $ workYears.
But there are differences in Object-Oriented Systems. when the public, protected, private, protected, or private attributes are used, _ is added as the difference.
public $startPosition = 1;protected $_salaryAmount =1000;private $_sex = 'formale';
2. if it is a constant, use uppercase letters and underscores in the middle to separate them.
define('CURRENT_SCRIPT', 'index.php');const TRANSACTION_TYPE = 'income';
3. for global variables, use a big camper and prefix with _. The first letter of all words is capitalized. Knowing the scope of a variable is very important, so local variables and global variables should be clearly separated!
$ _ System_Config;
$ _ Root_Path;
Indent character
For the indentation of the encoding, we use the tab indentation! Some may ask why space indentation is not applicable?
The reason is very simple. most editors support the number of spaces equal to the number of tabs, and there is no need to adjust the space!
Operator Number
All two-element operator numbers should be preceded by spaces.
$name = 'zero';$age > 18 ? 'adult' : 'children';
Common process statement planning
We agree that the curly braces of all flow statements occupy a single line. Reason: If you encounter complicated business logic, curly braces will be nested, so we will confuse the corresponding curly braces!
1. Branch statement
If ($ age >=18 & $ age <= 30) {echo 'Young man ';} else if ($ age> 30 & $ age <= 60) {echo 'midddle aged';} else {echo 'Old man ';} // the following code experts have a question: in the if statement, even if no curly braces are allowed, the curly braces should also be written into if ($ age> 60) {echo 'I am very old';} switch ($ status) {case 'forbiden ': echo 'login forbidden'; break; case 'normal': echo 'login '; break; default: echo 'status is wrong': break ;}
2. loop statements
while($condition){ statesments......;}foreach($arrayList as $arrayKey => $arrayItem){ states......;}do{ statements......; }while($condition)for($start; condition; changenumber){ statements......;}
2. writing specifications of comments
Many people say that the code does not need to be commented out. In fact, I think this is a very bullshit sentence (or he may be right, unless the entire team is alone, he has done everything without looking at other people's code ).
My personal opinion is: Write more comments. it is very friendly to others in the team or yourself!
Based on personal experience, annotations have at least the following functions:
1. it is helpful to improve the readability of the code. after all, reading your comments is much easier than reading your code!
2. it is helpful to plan your own code layout! This is because it is related to the types of code annotations. "Conducive to the layout of Code", this kind of things seems a bit suspended, simply saying it is not clear, we need real examples for support!
3. because our annotation specifications comply with the requirements of phpdocumentor, this tool can also generate a general description of the code, which is equivalent to a user manual! G
Types of code comments
1. Block comment
Block annotations are mainly used in three places. Descriptions of php scripts, descriptions of a large functional module, and comments that cannot be written within a row should also be placed in block comments.
2. line comment
Line comment. I personally think it works with block comment! It is generally used to describe the details of a large functional module!
Case studies
I will not talk about the specific usage details of the phpjavasentor syntax here. I can't go over it again on the official website.
From the above example, we can see how the code layout is, but we still need to explore it in practice.
The following are some php programming specifications for your reference.
I. file tag:
1. all php files use complete php labels for code marking. short labels are not recommended (short labels are easy to be confused with xml, and php does not support short tags by default from 5.4 ).
2. for php-only code files, we recommend that you omit '?> '. This is to prevent unnecessary spaces or other characters from affecting the code.
II. file and directory naming
1. the program file name and directory name are named in meaningful English. if you do not use pinyin or meaningless letters, only letters, numbers, underscores, and hyphens are allowed '. the end of php' (except for template files). multiple words use the hump naming method.
For example, DemoTest. class. php
// Use DemoTest. interface. php
// Other methods: demoTest. {style}. php
III. file directory structure
The standardized directory structure helps teams collaborate in development and post-maintenance.
-- App // independent application
-- Class // a single class file, a shared class file
-- Conf/inc // configuration file or directory
-- Data // data file or directory
-- Doc // program documentation
-- Htdocs // document_root
-- Images // path for storing all image files
-- Css // css file
-- Js // js file
-- Lib // shared class library
-- Template // template file
-- Tmp // temporary file directory
-- Cache // cache file
-- Session // SESSION file
-- Template_c // compiled template file
-- Other
-- Upload // upload a file
-- Manage // manage the file directory in the background
IV. naming rules
1. variable name: variables in php are case-sensitive. a valid variable name starts with a number, letter, or underline, followed by any number of letters, numbers, and underscores.
A) the program name should start with lowercase letters and be meaningful. (Function displayName ())
B) PHP global variable key values have '_' on both sides and are named in the middle using the hump naming method. ($ _ GLOBAL ['_ beginTime _'])
C) common variables use the hump naming method as a whole. we recommend that you add a prefix of the type before the variable. The uncertain type must start with an uppercase or lowercase character.
D) the function name should be meaningful and abbreviated as much as possible.
2. class and interface naming:
A) it must start with an uppercase letter.
B) variable names composed of multiple words. there is no interval between words. each word is capitalized.
C) the class name must be consistent with the class file name.
D) all the class names in the program are unique.
E) the Abstract class should start with Abstract.
Interface naming rules:
I) use the same naming rules as the class, but add the 'I' character before the naming to indicate the interface.
Ii) try to keep the class name consistent with the class name that implements it.
3. Database naming: all Database naming rules do not contain uppercase letters.
A) table names all use lowercase letters.
B) the table name uses the same prefix and the prefix cannot be blank.
C) use '_' to separate table names composed of multiple words.
D) table field naming rules.
I) use lowercase letters.
Ii) multiple words are separated by underscores.
Iii) prefix a common field with the first letter of the table name.
Iv) avoid using keywords and reserved words.
5. annotation specifications
1. program comment: write it in front of the code rather than behind it, and write a single line of code at the end of the code according to your habits. for a large part of the comment, use/**/, which is usually at the top of a file or function, '//' is used inside the code. too many comments should be used. the code comments should describe why rather than what is done, and provide the most important information to the code reader.
2. file comment: The file comment is usually placed on the top of the file, including the description, author, project name, file name, time and date, version information, and important instructions for use (class calls, note ). To modify the version, add the mofify annotation.
3. class and interface comments: According to common habits, a file contains only one class.
4. method and function comments: The comments of methods and functions are written before. it is usually necessary to indicate the main visibility, parameter type, and return value type of information.
/**
* Connect to the database
* @ Param string $ address of the dbhost database server
* @ Param string $ dbuser database username
* @ Param string $ dbpwd database password
*/
6. code style
1. indentation and space: four spaces are used as indentation without the Tab key. when values are assigned to variables, spaces are left on both sides of the equal sign. ($ Url = '$ _ GET ['URL']';)
2. statement line breaking: make sure that one line of the program statement is one; do not make the code of a line too long, less than 80 characters; if the code of a line is too long, use a line similar '. = 'disconnected rows; when performing SQL statement operations on the database, try not to write SQL statements in the function. Instead, use variables to define SQL statements, then, call the defined variable in the function that executes the operation.
3. better habits: use the methods listed below in the code to make the code more elegant.
1): use the existing constants in php instead of defining them by yourself.
Example: // line feed
Echo $ msg. "\ r \ n ";
Echo $ msg, PHP_EOL;
In php, PHP_EOL is a predefined constant that indicates the end of a row. different systems use PHP_EOL to make code more portable.
2): Using commas as the connector in echo is more beautiful than using '.' as the connector code.
3): the efficiency of single quotes is higher than that of double quotes, but the two are different in usage. learn to use the printf function.
Example: // echo
Echo 'every '. $ scholl.' has approximately '. floor ($ avg).' students ';
// Printf
$ Format = 'every % s is larger than $ d students ';
Printf ($ format, $ school, $ avg );
4): detailed notes
5): Do not abuse syntactic sugar. syntactic sugar is a hidden rule in the language, that is, it does not have a general representative syntax.