Why should we develop our own coding standards?
When we write code, a good coding standard can have many unexpected effects for us. At least there will be the following benefits:
1. Improve our coding efficiency. The neat and uniform code makes it easy for us to copy and paste!
2. Improve the readability of the code.
3. Show our professionalism. Others saw our code and found that the entire code writing process was neat and uniform, and they instantly became impressed!
4. Facilitate team collaboration. Everyone uses the same standard, which eliminates the various writing methods and ensures unified coordination!
Coding specifications include two major parts, code specifications and comment specifications
In fact, the PHP script we write is actually composed of two major parts, namely the writing of the code and the comments on the code! Different frameworks, and even different companies, will have different views on this aspect. This is just a summary of my own writing standards! I hope it can inspire other friends
1. Code writing standards
Name of the folder:
Use lowercase letters for folders. For example, if you store the folder of the controller, just name it controller
File naming:
If it is a class file, the file naming should be consistent with similar names and use large camel case. For example, Session.class.php, the corresponding class name is Session,
If it is an ordinary tool script, use small camel case, such as common.php
Name of class name:
The same class name uses camel case, Cookie class
Name of method name:
Use small camel case uniformly, and generally use the form of verb name to describe the function of the method, such as sendMessage, sending text messages.
In object-oriented, the same rules are followed, but there are some differences:
public getUserName() protected _getTotalAmount() private _setBlanceAmount()
Naming convention for variables:
We need to say a few more things about variables:
1. Whether in object-oriented or non-object-oriented syntax, variables use small camel case, such as: $workYears.
But it is different in object-oriented. When public, protected, private, protected or private attributes, _ is added in front as a difference
public $startPosition = 1; protected $_salaryAmount =1000; private $_sex = 'formale';
2. If it is a constant, use uppercase letters and use underscores to separate them.
define('CURRENT_SCRIPT', 'index.php'); const TRANSACTION_TYPE = 'income';
3. For global variables, use camel case, prefixed with _, and the first letter of all words is capitalized. Because it is very important to know the scope of a variable, local variables and global variables should be clearly separated!
$_System_Config;
$_Root_Path;
Indent character
Regarding the indentation symbols of encoding, we use tab indentation uniformly! Some people may ask why spaces are not used for indentation?
The reason is very simple. Most editors support the number of spaces equal to the tab character, and there is no need to adjust it when using spaces!
Operation symbols
All binary arithmetic symbols should be preceded and followed by spaces
$name = 'zero'; $age > 18 ? 'adult' : 'children';
Common process statement planning
We agree that the curly braces of all process statements occupy a separate line. Reason: If you encounter more complex business logic, there will be a lot of nesting of curly braces, 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 'middle aged'; } else { echo 'old man'; } //下面这段代码高手我们一个问题,在if语句中,即使在可以不要花括号的情况下,花括号也是要写上的 if($age > 60) { echo 'I am very old'; } switch($status) { case 'forbiden': echo 'login forbidden'; break; case 'normal': echo 'login in'; break; default: echo 'status is wrong' : break; }
2. Loop statement
while($condition) { statesments......; } foreach($arrayList as $arrayKey => $arrayItem) { states......; } do { statements......; } while($condition) for($start; condition; changenumber) { statements......; }
2. Writing specifications for comments
Many people say that good code does not need comments. In fact, I personally think this is a very nonsense statement (maybe he is right, unless he is the only one in the entire team, he does everything without looking at other people's comments) code).
My personal opinion is: writing more comments is very friendly to other people in the team and to yourself!
According to personal experience, comments have at least the following functions:
1. It helps to improve the readability of the code. After all, it is much easier to read your comments than your code!
2. Helps you plan your own code layout! The reason why I say this is because it is related to the type of code comments. "Conducive to the layout of the code", this kind of thing seems a bit confusing, it can't be explained by just saying it. We need real examples to support it!
3. Since our annotation specifications are in accordance with the requirements of PHPDocumentor, through this tool, we can also generate an overall description of the code, which is equivalent to an instruction manual! g
Types of code comments
1. Block comments
Block comments are mainly used in three places. When the description of a PHP script or a large functional module cannot be written in one line, it should also be placed in a block comment
2. Line comments
Line comments, personally think they work in conjunction with block comments! Generally used to describe the specific details of a large functional module!
Actual cases
Regarding the specific usage details of phpdocumentor syntax, I won’t go into details here. The official website can’t explain it more clearly
From the above example, we can take a look at the general layout of the code, but we still need to slowly explore it in practice
Attached below are some PHP programming specifications for your reference
1. File tag:
1. All PHP files use complete PHP tags for their code tags. It is not recommended to use short tags (short tags are easily confused with XML, and PHP does not support short tags by default starting from 5.4).
2. For code files that only have PHP, it is recommended to omit the ‘?>’ at the end. This is to prevent extra spaces or other characters from affecting the code.
2. File and directory naming
1. The program file names and directory names are all named in meaningful English. Pinyin and meaningless letters are not used. Only letters, numbers, underscores and underscore characters are allowed, and they must end with '.php' (Except for template files), use camel case naming between multiple words.
Example: //Uniform use of classes: DemoTest.class.php
//The interface is uniformly adopted: DemoTest.interface.php
//Others follow their own methods: demoTest.{style}.php
3. File directory structure
The standardized directory structure facilitates team collaboration development and post-maintenance.
——app //Independent application
——class //Single class file, shared class file
——conf/inc //Configuration file or directory
——data //Data file or directory
——doc //Program related documents
——htdocs //document_root
——images //All image file storage paths
——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 file
——manage //Backend management file directory
4. Naming convention
1. Variable naming: Variables in PHP are case-sensitive. A valid variable name starts with a number, letter, or underscore, followed by any number of letters, numbers, and underscores.
a) The entire program uses camel case naming, starting with a lowercase letter, and the name must be meaningful. (function displayName())
b) PHP global variable key values have ‘_’ on both sides, and are named in camel case in the middle. ($_GLOBAL['_beginTime_'])
c) Ordinary variables use camel case naming as a whole. It is recommended to add a prefix indicating the type before the variable. Undefined types start with an uppercase character.
d) Function names should be as meaningful as possible and abbreviated as much as possible.
2. Class and interface naming:
a) Start with a capital letter.
b) A variable name composed of multiple words, no space between words, and the first letter of each word is capitalized.
c) The class name should be consistent with the class file name.
d) All class names in the program are unique.
e) Abstract classes should start with Abstract.
Interface naming rules:
i) Use the same naming rules as classes, but add the ‘i’ character before the name to indicate the interface.
ii) Try to keep the name of the class that implements it consistent.
3. Database naming: In database-related naming, capital letters will never appear.
a) All table names use lowercase letters.
b) Table names use the same prefix and the prefix cannot be empty.
c) For table names composed of multiple words, use ‘_’ separation.
d) Table field naming rules.
i) Use all lowercase letters.
ii) Multiple words do not need to be separated by underscores.
iii) Prefix common fields with the first letter of the table name.
iv) Avoid using keywords and reserved words.
5. Comment specifications
1. Program comments: written in front of the code instead of behind. Single lines of code are written at the end of the code according to custom; large comments use /**/, usually at the top of a file or function, and '//' is used inside the code; comments should not be too many; code comments should describe why rather than what to do, providing the most important information to code readers.
2. File comments: File comments are generally placed at the top of the file, including the description of the program, author, project name, file name, time and date, version information, important usage instructions (class calls, precautions, etc.) . Version changes require modifying the version number and adding a mofify comment.
3. Class and interface notes: According to general habits, a file only contains one class.
4. Method and function annotations: Method and function annotations are written in front, and usually need to indicate the main visibility of the information, parameter types and return value types.
/**
* Connect to database
* @param string $dbhost Database server address
* @param string $dbuser Database username
* @param string $dbpwd Database password
*/
6. Code style
1. Indentation and spaces: Use 4 spaces for indentation and do not use the Tab key; when assigning values to variables, leave spaces on both sides of the equal sign. ($url = '$_GET['url']';)
2. Statement line breaking: Try to ensure that the program statement is one line; try not to make a line of code too long, within 80 characters; if a line of code is too long, please use a method similar to '.=' to break the line connection; execute When operating SQL statements in the database, try not to write SQL statements within the function. Instead, first define the SQL statement with variables, and then call the defined variables in the function that performs the operation.
3. Better habits: Use the methods listed below in your code to make your code more elegant.
1): Use constants that already exist in php instead of defining them yourself.
Example: //Line break
echo $msg."rn";
echo $msg,PHP_EOL;
PHP_EOL in php is a predefined constant, indicating the end of a line. Depending on the system used, the code using PHP_EOL is more portable
2): Using commas as connectors in echo is more beautiful than using ‘.’ as connector codes.
3): Single quotes are more efficient than double quotes, but there are differences in their use. Learn to use the printf function.
Example: //echo
Echo 'Each'. $ SCHOLL. 'There are about' .floor ($ avg). 'Student';
//printf
$format = 'Each %s has more than $d students';
printf($format,$school,$avg);
4): Detailed notes
5): Don’t abuse syntax sugar. Syntax sugar is the unspoken rules in the language, that is, grammar that is not universally representative.