PHP Coding Specification

Source: Internet
Author: User
Tags naming convention php script strcmp knowledge base

1. Introduction1.1. The important standardization issues of standardisation in some ways everyone has a headache and makes everyone feel that everyone is in the same situation. This helps to keep these recommendations evolving across many projects, and many companies spend weeks arguing by word-by-phrase. Standardization is not a special personal style, it is completely open to local improvement. 1.2. Advantages when a project tries to comply with common standards, there are the following benefits: • Programmers can learn any code and understand the state of the program · Newcomers can quickly adapt to the environment · Prevent new contact with PHP for time-saving needs, create a set of styles and develop lifelong habits · Prevent new people from contacting PHP making the same mistakes again and again In a consistent environment, people can reduce the chance of making mistakes · The programmers have the same enemies. 1.3. Disadvantages · Because standards are made by people who don't know PHP, standards usually look silly. Because the standard is not the same as I do, so the standard usually looks silly · The standard lowers creativity · Standards are not necessary for long-term co-operation among the people · Standard forced too many formats 1.4. The experience of discussing many projects can draw the conclusion that the adoption of programming standards can make projects more successful. Is the standard the key to success? Of course not. But they can help us, and we need all the help we can get! To be honest, much of the controversy over a standard of detail stems mainly from conceited thinking. Few decisions about a reasonable standard can be said to be a lack of technology, which is just the reason for the taste. So, be flexible and take control of your ego, and remember that any project depends on team work. 1.5. Explain the 1.5.1. The standard implementation should first identify all the most important elements within the development team, perhaps the criteria are not appropriate for your situation. It may have summed up important issues, and there may be some strong objections to some of those issues. No matter under what circumstances, as long as the final success, people will mature understand that the standard is reasonable, and then other procedures will find its reasonable * *, and feel that with some reservations to follow this standard is worthwhile. If there is no voluntary cooperation, the requirements can be established: standards must be tested by the code. Without testing, the solution is just a bunch of ridiculous people based on an imprecise base. 1.5.2. Identity View 1. It won't work; 2. Maybe it works, but it's neither practical nor boring; 3. It's true, and I've told you, 4. This is what I thought of first; 5. It's supposed to be like this. If you look at things with negative stereotypes, keep your mind open. You can still make it a nonsense conclusion, but the way to make a conclusion is that you have to be able to accept different ideas. Please give yourself a little time to do it. 1.5.3. Four stages of a project 1. Database Structure 2. Design 3. Data layer4. HTML Layer 2. Naming rules  2.1. Proper naming and naming is the core of program planning. The ancients believed that knowing a person's real name would gain an incredible power over that person. As long as you think of the right name for something, it will give you and later people a stronger power than the code. Don't laugh! A name is a long and far-reaching result of things in the ecological environment in which they are located. In general, only the programmer who understands the system can get the most appropriate name for the system. If all the names are compatible with their nature, then the relationship is clear, meaning can be deduced, and the general presumption can be expected. If you find that only a small amount of your name can match its counterpart, it's best to take a good look at your design again. 2.2. Class Naming · Before you name a class, you must first know what it is. If you still can't think of what this class is, if you provide clues through the class name, then your design is not good enough. A mixture of more than three words is prone to confusion among the entities of the system, and then look at your design and try to use the CRC Session card to see if the named entity has so many functions. The name of the derived class should avoid the temptation to take its parent class name, which is related only to itself and not to what its parent class is called. Sometimes the suffix is useful, for example: If your system uses a proxy (agent), then a part is named "Download Agent" (downloadagent) to actually transmit the information. 2.3. method and Function naming · Usually each method and function performs an action, so naming them should clearly explain what they do: Replace Errorcheck () with Checkforerrors () and Dumpdatatofile () instead of datafile (). Doing so can also make functionality and data more distinguishable. Sometimes the suffix name is useful: O Max-means the maximum value that an entity can give. o Cnt-The current value of a running count variable. O Key-key value. For example: Retrymax represents the maximum number of retries, and retrycnt represents the current number of retry attempts. Sometimes the prefix name is useful: O is-meaning to ask a question about something. Whenever people see is, they know it's a problem. o get-meaning to get a value. o set-meaning to set a value for example: Ishitretrylimit. 2.4. Do not use uppercase letters in all abbreviations · In any case, you can use the first letter to capitalize the remaining lowercase letters to represent abbreviations in lieu of all uppercase letters. Use: gethtmlstatistic. Not used: gethtmlstatisticReasons When names contain acronyms, people seem to have very different instincts. Uniform rules are the best, so that the meaning of naming can be fully predictable. As an example of networkabckey, note that C is the C in the ABC or in the key, which is very confusing. Some people don't care about this, others hate it. So you'll see different rules in different code, so you don't know how to call it. For example, class Fluidoz//Do not write Fluidozclass gethtmlstatistic//Do not write GetHTMLStatistic2.5. Class naming · Use uppercase letters as a separation of words, and all other letters in lowercase · First letter of first name use uppercase · Do not use underscores ('_') reasons · According to many naming methods, most people think this is the best way. such as Class Nameonetwoclass Name2.6. Class Library Naming · Currently, namespaces are being used more and more extensively to avoid conflicting class names between different vendors and group libraries. When namespaces are not yet in place, in order to avoid class name collisions, it is common practice to prefix the class name with a unique, two-character, and certainly a better one. For example, John Johnson's data structure class library can be prefixed with JJ, as follows: Class jjlinklist{} Another way to compromise is to build the inclusion Class Library directory (in fact, that's what Java does), to represent different namespaces in a directory that doesn't work. For example, Microsoft's database-related class libraries can be in:/classes/com/microsoft/database/dbconn.phpapache database-related class libraries available at:/classes/org/apache/database /dbconn.php2.7. Method naming · Use rules that are consistent with class naming · Most people who use all the different rules find this to be the best compromise. For example, Class Nameonetwo{function DoIt () {};function HandleError () {};} 2.8. Generic * * Name · The name of the genus * should be prefixed with the character ' M '. The prefix ' m ' is followed by a rule with a consistent class naming. ' m ' always modifies at the beginning of the name, as if it were a reference to the beginning of ' R '. Reasons The prefix ' m ' prevents any conflicts between generic * and method names. Your method name and genus name are often very similar, especially for accessing elements. For example, Class Nameonetwo{function varabc () {};function errornumber () {}var $mVarAbc; var $mErrorNumber; var $mrName;}  2.9. Parameter naming in Methods · The first character uses a lowercase letter. • All words after the first character are capitalized by the first character of the class naming convention. Reasons You can distinguish between generic variables in a method. You can use a name that is similar to the class name to avoid conflicting names. For example, Class Nameonetwo{function Startyourengines (& $rSomeEngine,& $rAnotherEngine);} 2.10. Variable name · Use lowercase for all letters · Use ' _ ' as the demarcation of each word. Reasons In this way, the scope of the variables in the code is clear. All variables look different in the code and are easily recognizable. For example function HandleError ($errorNumber) {$error = Oserr ($errorNumber); $time _of_error = Oserr->gettimeoferror (); $ Error_processor = Oserr->geterrorprocessor ();} 2.11. Reference variables and function return references · References must be prefixed with ' r ' for the reason · Make variables of different types easy to identify · It can determine which method returns the object that can be changed, and which method returns the immutable object. For example class Test{var mrstatus;function dosomething (& $rStatus) {};function &rstatus () {};} 2.12. Global Variables · Global variables should be prefixed with ' G '. Reasons It is important to know the scope of a variable. For example global $gLog; global & $grLog; 2.13. Defining named/Global Constants · Global constants separate each word with ' _ '. Reason this is the tradition of naming global constants. You should be careful not to conflict with other definitions. For example define ("A_global_constant", "Hello world!"); 2.14. Static variables · Static variables should be prefixed with ' s '. Reasons It is important to know the scope of a variable. For example, function test () {static $msStatus = 0;} 2.15. function naming · The function name uses the C GNU convention, with all letters using lowercase letters, using ' _ ' to split the words. Reasons This makes it easier to distinguish between the associated class names. such as FunctiOn Some_bloody_function () {}2.16. Error return detection rule · Check all system calls for error messages, unless you want to ignore the errors. Define the system error text for each system error message to include.3. Writing rules 3.1. There are two types of braces {} rules that are acceptable in the three main braces placement rules, the first of which is the best: · Place curly braces at the same column below the keyword: if ($condition) while ($condition) {{...}} The traditional Unix parentheses rule is that the first parenthesis goes with the keyword, and the end bracket is the same as the keyword: if ($condition) {while ($condition) {...}} Reasons The non-principled problems that cause the violent controversy can be solved by means of compromise, either of which is acceptable, but for most people the first one is preferred. The reason is that psychology studies the category of learning things. There are more reasons for liking the first. If you use a character editor that supports brace matching (for example, VI), the most important thing is to have a good style. Why? We say when you have a big program and want to know where this big program ends. You first move to the opening parenthesis and press the button editor to find the closing parenthesis, for example: if ($very _long_condition && $second _very_long_condition) {...} else if (...) {...} Moving from one program block to another requires you to match the key with the cursor and your parentheses, without looking for matching parentheses. 3.2. Indent/tab/space rules · Use tab indent. Use three to four spaces to indent each level. No longer use a method that shrinks as soon as it is needed. For the maximum indent layer, there is no fixed rule, if the number of indentation layer is greater than four or five layers, you can consider the code factor decomposition (factoring out codes). Reasons Many programmers support tabs. When people use a tab standard that is too different, it makes reading code very laborious. So many people are willing to limit the maximum indentation level, which is often never seen as a job. We believe that programmers will choose the depth of nesting wisely. For example, the function func () {if (something bad) {if (another thing bad) {while (more input) {}}}}3.3. Parentheses, keywords, and function rules · Don't put parentheses and keywords close together, separate them with a space. Don't put parentheses and function names close together. Do not use parentheses in return return statements unless necessary. Reasons The keyword is not a function. If the parentheses are close to the function name and the keyword, they can easily be considered as one. For example if (conditioN) {}while (condition) {}strcmp ($s, $s 1); return 1;3.4. Do not do the actual work in the object schema function do not do the actual work in the object schema constructor, the constructor should contain the initialization of variables and/or do not fail the operation. Reasons The construct cannot return an error. For example, Class Device{function Device () {/* Initialize and other stuff */}function Open () {return FAIL;}};   $dev = new Device;if (FAIL = = $dev->open ()) exit (1); 3.5. If then Else format Layout This is determined by the programmer. The different curly brace styles produce slightly different views of the sample. A common way is: if (condition 1)//Comment {}else if (condition 2)///Comment {}else//comment {} If you are useful to an else if statement, it is usually preferable to have an else block to handle other cases that are not processed. If you can put a record information note in the else place, even if there is no action in else. Conditional formatting always places the constant on the left side of the equal sign/non-equal sign, for example: if (6 = = $errorNum) ... One reason is that if you miss an equal sign in the equation, the grammar checker will give you an error. The second reason is that you can immediately find the value instead of finding it at the end of your expression. It takes a little time to get used to the format, but it's really useful. 3.6. Switch Format · When a case block is processed, it goes directly to the next Case block processing, which should be annotated at the end of the case block. The default case should always exist, it should not be reached, however if it arrives it will trigger an error. If you want to create a variable, put all the code in the block. For example, switch (...). {Case 1:...//FALL throughcase 2:{$v = Get_week_number (); ...} break;default:}3.7. Continue,break and? The use of 3.7.1. Continue and Breakcontinue and break are in fact disguised, covert goto methods. Continue and break are like Goto, they are magical in code, so use them sparingly (as little as possible). Using this simple magic, due to some undisclosed reasons, the reader will beDirected to places that only God knows. Continue has two main questions: · It can bypass test conditions. It can bypass equal/unequal expressions. Take a look at the following example, and consider where the problem occurs: while (TRUE) {...//A lot of code...if (/* Some condition */) {continue;} ...//A lot of Code...if ($i > Stop_value) break;} Note: "A lot of code" is required to make it difficult for programmers to find errors. From the above example, we can draw further rules: Continue and break mixed use is the right way to cause disaster. 3.7.2: The trouble is that people often try to And: Crammed a lot of code between them. Here are some clear rules for connecting: • Put the condition in parentheses so that it is separated from the other code. If possible, actions can be made with simple functions. Put the action, "?", ":" On a different line, unless they can be clearly placed on the same line. For example (condition)? Funct1 (): Func2 (); or (condition)? Long Statement:another long statement;3.8. Positioning of the declaration block · Declares that code blocks need to be aligned. Reasons Clear. • A similar code block for variable initialization should be listed. & should be near the type, not the variable name. For example var $mDatevar & $mrDatevar & $mrNamevar $mName $mdate = 0; $mrDate = NULL; $mrName = 0; $mName = null;3.9. One statement per line unless the statements are closely related, only one statement per line is written. 3.10. The short method method code is limited to one page. 3.11. Record all empty statements always record a for or a while empty block statement, in order to know clearly that the code is missing, or deliberately do not write. while ($dest = $SRC); VOID3.12. Do not use the default method to test non-0 values do not test non-0 values by default, that is, if (fail! = f ()) is better than the following method: if (f ()) Even if FAIL can contain 0 values, that is, the expression PHP considers false. An explicit test can help you when someone decides to use 1 instead of 0 as the return value of the failure. The comparison value does not change, andAn explicit comparison should be used, for example: if (! ( $bufsize% strlen ($STR))) should be written as: if (($bufsize% strlen ($str)) = = 0) to indicate the numeric (not Boolean) type of the test. A common problem is to use strcmp to test a character equation, and the result will never be equal to the default value. Non-0 tests take a default-based approach, and other functions or expressions are subject to the following limitations: • Only 0 is returned to fail, and no other value is available. The name so that the return value of a true (true) is absolutely obvious, calling the function IsValid () instead of Checkvalid (). 3.13. Boolean logic type Most functions return 0 when FALSE, but a non-0 value represents TRUE, so do not use the 1 (true,yes, etc.) equation to detect a Boolean value, instead of 0 (False,no, and so on) inequalities: if (TRUE = = Func ()) {... Should be written as: if (FALSE! = Func ()) {... 3.14. Usually avoid the embedded assignment sometimes in some places we can see embedded assignment statements, those structures are not a relatively good less redundant, readable * * Strong method. while ($a! = ($c = GetChar ())) {process the character} and---operator is similar to an assignment statement. Therefore, for many purposes, there are side effects when using a function. It is possible to use embedded assignments to improve runtime * *. In any case, the programmer needs to consider the tradeoff between the speed of growth and the reduced maintainable * * When using embedded assignment statements. For example: a = b c;d = a r; do not write: D = (a = b c) r; Although the latter can save a cycle. But in the long run, as the maintenance costs of the program grow, the writers of the program gradually forget about the code, reducing the optimal results at maturity.4. Help and Sharing4.1. Reusing the hard work of you and others cross-engineering reuse is almost impossible without a common structure. Objects meet their existing service requirements, and different processes have different service requirements environments, making object reuse difficult. Developing a common structure requires a lot of effort to design in advance. When efforts are unsuccessful, for whatever reason, there are several ways to recommend using: 4.2. Ask! The simple way to send email to a group is rarely used. Because some programmers think that if he turned to other people for help, he would appear to be low level, this is silly! Do new and interesting work, do not do the things that others have done over and over again. If you need a source code for something, send an email to the group if someone has already done it. The results will be very pleasantly surprised Oh! In many large groups, individuals often don't know what other people are doing. You can even find someone looking for something to do and volunteer to write code for you, and if people work together, there's always a gold mine out there. 4.3. Tell! When you're doing things, tell everyone if you've done something that you can reuse and let others know. Don't be shy, and don't hide your work to protect your pride. Once you develop the habit of sharing your work, everyone gets more. 4.4. Small code base for code reuse, a common problem is that people do not make libraries from the code they do. A reusable class might be hiding in a program directory and never be excited about being shared, because programmers don't split classes into libraries. One of the reasons for this is that people do not like to make a small library, and have some incorrect feeling about the small library. Get rid of this feeling and the computer doesn't care how many libraries you have. If you have some code that can be reused and cannot be placed in a library that already exists, then make a new library. If people really think about reuse, the library won't stay that small for a long time. 4.5. Knowledge Base Many companies do not know what code is available, and most programmers still do not communicate what they have done, or have been asking what code is available. The way to solve this is to have a knowledge base available. Ideally, programmers can go to a Web page, browse or query the list of packaged repositories to find what they want. It is a good practice to build a knowledge base system that can be automatically maintained by programmers. If you have a dedicated administrator who is responsible for maintaining this knowledge base, it's certainly better. Another approach is to automate the process of generating a knowledge base from code. Use generic classes, methods, and headers (subsystem headers) as manuals or as an entry in the Knowledge Base.5. Writing notes 5.1. Tell a story about your comments as a story describing the system. and allows your annotations to be parsed by the machine and placed in a manual in a fixed format. The comments of the class are part of the story, the name of the method, the comment of the method, and the implementation of the method are also part of the story. All of these pieces are woven together, making it possible for people to know exactly what you did in the future and why. 5.2. Archive comment notes to be archived makes sense, otherwise, if you put a comment in one place describing what choices you have made and why you did it, only archaeologists can find this to be the most useful information. (How to file a separate specification) 5.3. Note Each part of the structural engineering has a specific annotation structure. Note In the program, where the example is given as a specification, with the start of the keyword "@" in the note, ending with the comment keyword. 5.3.1. predefined keyword keywords meaning purpose represents a class, a * *, a method to do something or what it means. Package Name Class name author author modifications modify record (number sequence is "no" + Date + "-" + serial number) See Reference method name Method name parameter parameter name (including type) Return return value (including type) attribute/variable name genus **/variable name type genus **/variable 5.3.2. Class Comment/*** @ purpose:* The class that accesses the database, with ODBC as the generic provider * @Package name:database* @Author: Forrest Gump [email protected]* @Modif ications:* no20020523-100:* odbc_fetch_into () parameter position second and third position exchange * John Johnson [email protected]* @See: (Reference) */class Database{...} 5.3.3. Method comments/*** @Purpose:* Execute a query * @Method name:query () * @Parameter: string $queryStr SQL query String * @Return: Mixed query return value (result set pair Like) */function ($QUERYSTR) {...} 5.3.4. Genus * or variable comment/*** @Purpose:* database connection user name * @Attribute/variable name:mdbusername* @Type: StrinG*/var mdbusername;5.3.5. if (0) to comment the external code block sometimes needs to annotate the large section of the test code, the simplest way is to use the if (0) Block: function Example () {great looking codeif (0) {Lots of Code}more code} You cannot use/ **/, because annotations cannot be included inside a comment, and a large segment of a program can contain comments. 5.3.6. The directory document must have a Readme document in all directories, including: • The functionality of the directory and what it contains · An online description of each file (with link), and each description should usually also extract some of the name of the file header. • Includes settings, instructions for use · Guide people how to connect related resources: o source file index o document o paper document o design documentation · Other things that help the reader think about it, when each of the original engineers was gone, a newcomer in 6 months, the lone frightened explorer through the project's source code tree, read the documentation, the source file header description and so on as a map, he should have the ability to cross the entire project.6. Other · Adopt object-oriented design method; There is no doubt that this is the closest way to people's natural thinking, it may feel that there is no direct writing in the early days, can you try to keep your opinion? It's in the back!. The definition of a class takes a file class, and the class name and file name are the same; O more and more people have accepted this practice o it turns out that this approach makes the logical structure of the project clearer · In a class definition file, an output statement such as Echo and print must not appear outside the definition body, and the reason for such a statement should appear as a bug. The output page page does not appear on the SQL statement reason this is the N-layer structure of the programming idea, each layer of the task is different, although can be ultra vires exercise, may be so fast, but we do not agree to do so. Data for SQL execution must be valid * * Detect special symbols: For MS SQL Server, the '%_[' symbols are special meaning characters written in SQL statements that need to be processed before SQL is executed. Script symbols: For PHP script tags, such as <?? ><%%><?php?><script lang<script language= "php" &GT;&LT;/SCRIPT&GT; you need to detect processing before entering the database. Reason this is a convention for database programming, which is what many reference books say, which needs to be emphasized here. Avoid inserting PHP code Loop code and pure variable output (similar to <?= $UserName?>) in HTML pages. The reason o need to explain is that we work upstream, page designer's work, if the page interspersed with code, will destroy the structure, this should be we need to avoid. o The PHP code here is only responsible for showing that the extra code is obviously not supposed to be. A number without meaning a naked number used in the source code is an incredible number, because it includes the author, within three months, no one has its meaning. For example: if (= = $foo) {Start_thermo_nuclear_war ();} else if (= = $foo) {Refund_lotso_money ();} else if (+ = $foo) {infinite_loop ();} else {cry_cause_im_lost ();} What are the meanings of 22 and 19 in the above example? What would you think if a number had changed, or if the numbers were simply errors? Using incredible numbers is an important sign that the programmer is an amateur athlete. You should use define () to give you a real name for the value you want to represent something, not a naked number, such as: Define ("President_went_crazy", "a");d efine ("we_goofed", "n");d efine ("They_didnt_pay", "+"); if (President_went_ CRAZY = = $foo) {Start_thermo_nuclear_war ();} else if (we_goofed = = $foo) {Refund_lotso_money ();} else if (They_didnt_pay = = $foo) {infinite_loop ();} else {happy_days_i_know_why_im_here ();} Don't you get better now?7. php File name extensionCommon PHP files have the following extensions: HTML,. php,. PhP3,. PhP4,. Phtml,. Inc,. Class ... Here we agree: · All browser visible pages are used. HTML All classes, function library files are used. PHP reasons · The extension describes the type of data that the user will receive. PHP is interpreted as HTML.8. PHP Code TagsUnified use of <?php, only output variables when <?= $username?>

PHP Coding Specification

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.