In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to cultivate their own php coding specifications", in daily operation, I believe many people have doubts on how to cultivate their own php coding specifications, Xiaobian consulted all kinds of information, sorted out simple and easy to use operation methods, hope to answer "how to cultivate their own php coding specifications" doubts helpful! Next, please follow the small series to learn together!
Why should we develop our own coding conventions?
When we write code, a good coding specification can have a lot of unintended effects for us. There are at least some benefits:
1. Improve our coding efficiency. Uniform code convenient for us to copy and paste it!
2. Improve readability of code.
3. Show us our professionalism. When others saw our code, they found that the entire code writing process was uniform, and they instantly went up!
4. Facilitate team collaboration. Everyone uses the same standard, which eliminates the five flowers and eight points of writing, the same coordination!
The coding specification consists of two large blocks, the code specification and the comment specification.
In fact, the PHP script we wrote is actually composed of two large blocks, namely, the writing of the code and the comments on the code! Different frameworks, even different companies, will be different in this regard, here is just a general statement, just a summary of their own writing norms! Hope to inspire other friends
1. Code writing specification
Folder naming:
Use lowercase letters for folders. For example, the folder where the controller is stored can be named controller directly.
Name of file:
If it is a class file, then the naming of the file should be consistent with the name of the same class, and the unified use of large humps. For example, Session.class.php , the corresponding class name is Session,
If it is a common tool script, then use small humps uniformly, such as common.php
Name of class name:
Class Name Same Use Big Hump, Cookie Class
Name of method name:
Uniform use of small humps, generally use the verb + ranking form to describe the function of the method, such as sendMessage, send short messages.
In object-oriented, the same rules are followed, but with a few differences:
public getUserName()protected _getTotalAmount()private _setBlanceAmount()
Naming conventions for variables:
We need to say a few more things about variables:
Whether in object-oriented or non-object-oriented syntax, variables use small humps, such as: $workYears.
However, in object-oriented, there is a difference. When public, protected, private ,protected or private attributes are added in front of_as a distinction.
public $startPosition = 1;protected $_salaryAmount =1000;private $_sex = 'formale';
2. If it is a constant, use capital uniformly, and use underscore in the middle to divide it.
define('CURRENT_SCRIPT', 'index.php');const TRANSACTION_TYPE = 'income';
3. Global variables, use large humps, prefix with_ , and capitalize all words. Because it is important to know the scope of a variable, local and global variables should be clearly separated!
$_System_Config;
$_Root_Path;
indent
For coding indentation symbols, we use tab indentation uniformly! Some people may ask why space indentation is not applicable?
The reason is very simple, most editors support tabs equal to the number of spaces, and the use of spaces can not be adjusted!
sign of operation
All binary operators should be preceded and followed by spaces
$name = 'zero';$age > 18 ? 'adult' : 'children';
Common Process Planning Statements
We agreed that all flow statements have curly braces on a single line. Reason: If you encounter more complex business logic, curly brackets will appear a lot of nesting, so we will confuse the corresponding curly brackets!
1. Branching statements
if($age >= 18 && $age 30 && $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. Circular statements
while($condition){ statesments......;} foreach($arrayList as $arrayKey => $arrayItem){ states......;} do{ statements......; }while($condition)for($start; condition; changenumber){ statements......;}
2. Writing standards of notes
Many people say that good code does not need comments, in fact, personally think this is a very nonsense words (or he may be right, unless the whole team is his own person, he does everything, do not have to look at other people's code).
My personal opinion is: Write comments more often, whether to the rest of the team or to yourself is very friendly!
From personal experience, comments have at least the following effects:
1, conducive to improving the readability of the code, after all, reading your comments than reading your code to be much easier!
2, conducive to planning their own code layout! The reason for this is because it has to do with the type of code comments. "Favorable layout of code", this kind of thing looks a little hanging, just can't say clearly, we need real examples to support!
Since our annotation specification is in accordance with the requirements of phpdocumentor, through this tool, you can also generate an overall description of the code, equivalent to a manual! g
Types of code comments
1. Block comment
I think it is mainly used in three places. Description of php script, description of a large functional module, comments that cannot be written in one line, should also be placed in block comments
2. Line comments
Line comments, I think he is working with block comments! Generally used to describe the details of a large functional module!
Practical cases
About the specific use of phpdocumentor syntax details, here is not much to say, the official website said it is very clear
From the above example we can see what the layout of the code is about, but we still need to slowly explore in practice
Below are some php programming specifications attached for your reference
I. Document marking:
1. All php files, their code tags are full php tags, short tags are not recommended (short tags are easy to confuse with xml, php does not support short tags by default since 5.4).
2. For php-only code files, it is recommended to omit the '?> at the end '。This is to prevent extra spaces or other characters from affecting the code.
II. File and directory naming
1. Program file names and directory names are named in meaningful English. Pinyin and meaningless letters are not used. Only letters, numbers, underscores and underlined characters are allowed. At the same time, they must end with '.php'(except template files). Hump naming method is used between multiple words.
For example://class unified use: DemoTest.class.php
//Interface unified use: DemoTest.interface.php
//Others in their own way: demoTest. {style}.php
III. File Directory Structure
A regular catalog structure facilitates collaborative team development and post-maintenance.
--app //standalone app
--class //individual class files, shared class files
--conf/inc //configuration file or directory
--data //data file or directory
--doc //Process-related documentation
--htdocs //document_root
--images //all image file storage path
--css //css file
--js //js file
--lib //Common class libraries
--template //template file
--tmp //temporary file directory
--cache //cache files
--session //SESSION file
--template_c //compiled template file
--other
The requested URL/upload /was not found on this server.
--manage //manage file directory in background
IV. Nomenclature
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, or underscores.
a) The program as a whole is named with humps, starting with lowercase letters, and the name is meaningful.(function displayName())
b) PHP global variable keys have '_' on both sides, with hump naming in the middle.($_GLOBAL['_beginTime_'])
c) The hump naming method is adopted for common variables as a whole. It is recommended to add a prefix indicating type before variables. Indeterminate type begins with an upper-case character.
d) Function names should be as meaningful as possible and abbreviated as possible.
2. Class and interface naming:
a) Start with a capital letter.
b) Variable names composed of multiple words, with no spaces between words, and the first letter of each word is capitalized.
c) Class names are consistent with class file names.
d) All class names in the program are unique.
e) Abstract classes should begin with Abstract.
Interface naming rules:
i) Adopt the same naming convention as classes, but preceded by the character 'i' to indicate interfaces.
ii) Try to keep and implement its class name consistent.
3. Database naming: In database-related naming, capitalization does not appear.
a) Use lowercase letters for table names.
b) The table name uses the same prefix and the prefix cannot be empty.
c) For multi-word table names, use '_' spacing.
d) Table field naming convention.
i) Use all lowercase letters.
ii) Multiple words are separated without underlining.
iii) Prefix common fields with the initials of the table name.
iv) Avoid keywords and reserved words.
V. Specification of Notes
1. Program comments: written at the beginning of the code rather than at the end, single-line code is written at the end of the code according to custom; large comments are written in/** /, usually at the top of a file or function, inside the code using '//'; comments should not be too much; code comments should describe why rather than what to do, to provide the most important information to the code reader.
2. File notes: file notes are generally placed at the top of the file, including the program description, author, project name, file name, date, version information, important instructions (class calls, precautions, etc.). Version changes are made by modifying the version number and adding a moify comment.
3. Class and interface comments: By convention, a file contains only one class.
4. Method and function comments: Method and function comments are written at the front, usually indicating the primary visibility of the information, parameter types, and return value types.
/**
* connect to the database
* @param string $dbhost Database server address
* @param string $dbuser database username
* @param string $dbpwd database password
*/
VI. Code Style
1. Indents and spaces: Use 4 spaces for indentation, no Tab key; when assigning variables, leave spaces on both sides of the equal sign.($url = '$_GET['url']';)
2. Statement line break: try to ensure that the program statement is a line; try not to make a line of code too long, within 80 characters; if a line of code is too long, please use something similar to '.= When executing sql statement operations in the database, try not to write sql statements in the function, but first define sql statements 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 it more elegant.
1) Use constants that already exist in PHP instead of defining them yourself.
Example://newline
echo $msg. "\r\n";
echo $msg,PHP_EOL;
PHP_EOL in php is a predefined constant that indicates the end of a line. Depending on the system used, PHP_EOL code is more portable.
2): Use commas as connectors in echo instead of '. 'It's better to make connector codes.
3): The efficiency of single quotation marks is higher than double quotation marks, but there are differences in the use of the two, learn to use the printf function.
Example://echo
echo 'each'.$ scholl. 'about'. floor($avg). 'a student';
//printf
$format = 'each %s has more than $d students';
printf($format,$school,$avg);
4): Detailed comments
5): Don't abuse grammatical sugar, grammatical sugar is the hidden rules in language, that is, grammar that does not have universal representation.
At this point, the study of "how to cultivate your own php coding specification" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.