Develop your own PHP coding specifications _php Skills

Source: Internet
Author: User
Tags coding standards comments php programming php script uppercase character

Why do we have to develop our own coding standards?

When we write code, a good coding code, for us to be able to play a lot of the effect of no intention. At least there will be the benefits:

1, improve our coding efficiency. Uniform code is convenient for us to copy and paste!
2, improve the readability of the code.
3, show our professional. Others see our code, found that the entire code of the writing process is uniform, the instant force lattice went up!
4, facilitate the team work together. Everyone uses the same specification, which eliminates the five spend eight points of writing, the same coordination!

The coding specification contains two chunks, code specifications and annotation Specifications

In fact, we write PHP script, in fact, is composed of two large chunks, that is, the code of the writing, comments on the code! Different frameworks, and even different companies, in this respect will be different, here is just the words, just to their own writing norms to carry out a summary! I wish I could be a revelation to other friends.

1, Code of writing specifications

Name of folder:

The folder uses lowercase letters the same. If the folder that holds the controller, directly named Controller can

Name of File:

If it is a class file, then the name of the file should be consistent with similar names, unified use of large humps. such as Session.class.php, the corresponding class name is session,
If it's an ordinary tool script, then use a small hump like common.php

Naming of class names:

Class name same use big hump, Cookie class

Name of method Name:

Unified use of small hump, generally use the form of verb + rank to describe the function of the method, such as SendMessage, send text messages.
In object-oriented, follow the same rules, but differ in individual places:

Public GetUserName ()
protected _gettotalamount ()
private _setblanceamount ()

The naming specification for variables:

We need to say a few more things about variables:
1, whether in object-oriented or non-object-oriented syntax, variable unified use of small humps, such as: $workYears.
But in the object-oriented and different, public, protected, private, protected or private attributes, the front plus _ as a difference

public $startPosition = 1;

protected $_salaryamount =1000;

Private $_sex = ' Formale ';

2, if the constant, the unified use of uppercase, the middle of the use of underline to split.

Define (' Current_script ', ' index.php ');

Const TRANSACTION_TYPE = ' income ';

3, the global variable, using the big hump, prefix plus _, all the words first letter capital. Because it is important to know the scope of a variable, local variables and global variables should be clearly separated!

$_system_config;

$_root_path;

Indent character

About the encoding of the indent symbol, we uniformly use the tab indent! Perhaps some people will ask why does not apply the space indent?
The reason is simple, most editors support tabs equal to how many spaces, and the use of space is not adjusted!

Operational symbols

All two-dollar operation symbols should be used before and after the space

$name = ' zero ';
$age > 18? ' Adult ': ' Children ';

Common Process Statement Planning

We have agreed that all the curly braces for the process statements occupy a single row. Reason: If you encounter more complex business logic, curly braces will appear a lot of nesting, so we will confuse all the corresponding curly braces!

1. Branch statements

if ($age >= && $age <=) 
{
  echo ' young man ';
}
else if ($age > && $age <=)
{
  echo ' middle aged ';
}
else
{
  echo ' old man ';
}

The following code master we have a problem, in the IF statement, even if you can not curly braces, the curly braces are to be written on the
if ($age >)
{
  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. The writing specification of the annotation

Many people say that the code is not need to annotate, in fact, personally think it is a very nonsense words (or maybe he is right, unless the whole team he alone, he arranged everything, do not look at other people's code).

The personal point of view is: Write more notes, whether it is for the team of other people, or for themselves are very friendly!

According to personal experience, annotations have at least the following effects:

1, to improve the readability of the code, after all, read your comments than to read your code is much easier!
2, conducive to planning their own code layout! The reason for this is that it is related to the type of code annotation. "In favor of the layout of the code", this look a little hanging thing, the light said is not clear, we need real examples to do support!
3, because our annotation specification is in accordance with the requirements of phpdocumentor, so through this tool, you can also generate a general description of the code, equivalent to a user manual! G

Types of code comments

1. Block annotation
Block notes, which are personally believed to have been used in three places. The description of the PHP script, the description of a large functional module, and the inability to finish the comment within a row should also be placed in a block comment

2, Line comments
Line comment, personally think he is working with block annotations! Generally used to describe the specific details of a large functional module!

The case of actual combat

About the specific use of phpdocumentor grammar details, here is not much to say, the official network said more clearly

From the example above we can look at the layout of the code roughly, but we need to explore it in practice.

Here are some PHP programming specifications, for you to refer to the following

First, the document marking:

1. All php files, their code tags are complete PHP tags, do not recommend the use of short tags (short tags easy and xml confusing, PHP from 5.4 to start by default does not support short tags).

2. For PHP-only code files, it is recommended to omit the '?> ' at the end. This is to prevent extraneous spaces or other characters from affecting the code.

Second, file and directory naming

1. The program file name and directory name are in a meaningful English name, do not use pinyin and meaningless letters, only allow letters, numbers, underscores and underlined characters, and must end with '. php ' (except template file), multiple words between the use of the hump naming method.

Example://Class Unified use: DemoTest.class.php

Interface Unified Adoption: DemoTest.interface.php

Others in their own way: Demotest. {style}.php

Third, file directory structure

The canonical directory structure facilitates team collaboration development and later maintenance.

--app//Independent applications

--class//single class files, shared class files

--conf/inc//config file or directory

--data//Data file or directory

--doc//Program related documents

--htdocs//document_root

--images//All picture file storage path

--css//css File

--js//js File

--lib//Shared class Library

--template//Template files

--TMP//Temporary Files directory

--cache//cache files

--session//session File

--template_c//Compiled template files

--other

--upload//Uploading files

--manage//Admin file directory

Four, naming norms

1. Variable naming: Variables in PHP are case-sensitive, and a valid variable name begins with a number, letter, or underscore followed by any number of letters, numbers, and underscores.

A the whole program is named after the hump, starting with a lowercase letter, and naming meaningful. (function DisplayName ())

b The PHP global variable key value Both sides have ' _ ', the middle by the hump naming method. ($_global[' _begintime_ '])

c The general variable of the overall use of the Hump naming method, proposed in the variable prefix of the expression type. An indeterminate type begins with an uppercase character.

d) function name to be as meaningful as possible, abbreviated.

2. Class and interface naming:

A) begins with a capital letter.

b A variable name consisting of multiple words, with no spacing between the words, and the first letter of each word capitalized.

c) The class name is consistent with the class file name.

d) All class names in the program are unique.

e) Abstract classes should begin with abstract.

Interface naming rules:

(i) Adopt the same naming rules as the class, but add ' I ' to the name before it represents the interface.

II try to maintain and achieve its class name consistent.

3. Database naming: In database-related naming, there is no capitalization.

A the table name uses lowercase letters.

b The table name uses the same prefix and the prefix cannot be null.

C for a table name consisting of multiple words, use the ' _ ' interval.

d) table field naming rules.

i) all use lowercase letters.

ii Multiple words are not separated by an underscore.

(iii) prefix commonly-known fields with table-first letters.

IV) Avoid using keywords and reserved words.

V. Specification of annotations

1. Program annotation: Written in front of the code rather than behind, a single line of code is written at the end of the code by habit, and large notes are/**/, usually at the top of a file or function, with '//' within the code, with too many comments, and code comments should describe why rather than what to do, giving the reader the most important information.

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 date, version information, important use instructions (class calls, precautions, etc.). Version changes to modify the version number and add mofify comments.

3. Class and interface annotations: According to general practice, a file contains only one class.

4. Methods and Function notes: comments for methods and functions are written in the preceding, and usually need to indicate the primary visibility, parameter type, and return value type of the information.

/**

* Connect to the database

* @param string $dbhost database server address

* @param string $dbuser database user name

* @param string $dbpwd database Password

*/

Six, code style

1. Indents and Spaces: use 4 spaces for indentation, without using the TAB key; When a variable is assigned, a space is left on both sides of the equal sign. ($url = ' $_get[' url '] ';)

2. Sentence break: Try to ensure that the program statement line is one sentence; try not to make a line of code too long, 80 characters or less; if the line's code is too long, use a break-through connection similar to '. = ', and try not to write SQL statements in the function when you execute SQL statement operations on the database Instead, define the SQL statement with a variable, and then call the defined variable in the function that performs the action.

3. Better habits: Use the methods listed below in your code to make your code more elegant.

1): Use the constants that already exist in PHP, rather than defining them yourself.

Example://Line Wrapping

echo $msg. " \ r \ n ";

Echo $msg, Php_eol;

Php_eol in PHP is a predefined constant that indicates the end of a row and uses Php_eol code to be more portable as the system is used differently

2): Use commas in echo to make connectors, rather than '. ' Make connector code more beautiful.

3): Single quotes are more efficient than double quotes, but they differ in their use and learn to use printf functions.

Example://echo

Echo ' each '. $scholl. ' About floor '. ($avg). ' A student ';

Printf

$format = ' Each%s is greater than a $d student ';

printf ($format, $school, $avg);

4): Detailed notes

5): Do not abuse the grammatical sugar, grammatical sugar is the unspoken rules of language, that is, does not have universal representation of the grammar.

Related Article

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.