search
HomeBackend DevelopmentPHP TutorialPHP Coding Standard PHP Coding Standard_PHP Tutorial

PHP Coding Standard PHP Coding Standard_PHP Tutorial

Jul 21, 2016 pm 02:57 PM
phpprefixin principlenamemeanKnowexpressspecificationSemanticsUniversal

General principles:
1. Semantic
When you see the name, you know the meaning.

2. The common prefix
is means whether, get means reading, and set means writing. is is followed first by adjectives rather than nouns. For example, if the text is multilingual, is_multilingual should be used instead of is_multilanguage.

3. Singular and plural
Refer to the function naming rules of js: getElementById, getElementsByTagName, getElementsByName.
For example:
To get the names of my multiple friends, you should use getFriendsName instead of getFriendNames or getFriendName
To get a user, getUser
To get multiple users, getUsers

4. Redundant suffixes
Try not to use data, list, and info suffixes.
For example, pay attention to the naming of js, use getElementsByTagName instead of getElementsInfoByTagName.
You should use getFriends or getFriendsUserId instead of getFriendsList; you should use getUser instead of getUserInfo or getUserData.
But sometimes it’s hard to avoid it. For example, there are two functions, one is to get the user’s basic information, and the other is to get the user’s detailed information.
Get basic user information: nickname, avatar URI, function name getUserBasic or getUserBasicInfo? It feels inappropriate for the function name to end with an adjective, to be discussed.
Get user details: nickname, avatar URI, signature, birthday, function name getUser is no problem.

5. Ambiguous class names, file names, and directory names
Be careful whenever you use common, util, functions, class, object, and basic as file names, because these words are too common and difficult to develop. As you go down, there may be more and more stuff inside, turning it into a trash can. Give these an accurate name. For example, a class that does string processing can be called StringLib.php and placed in the lib directory.

6. The difference between lib, plugin and addon
Some classes and functions are counted as lib, plugin or addon. To be discussed.

Class name:
Start with a capital letter and use camel case. Generally use nouns, such as configuration parsing class ConfigParser instead of ParseConfig.
Same as Java and C++.
For example: class UserModel

The file name of the class:
is the same as the class name. This is related to php autoload. For autoload, the class name must always be very long, to be discussed.
Consistent with Java.
For example: the file name of class UserModel is UserModel.php

Non-class file name:
All lowercase, separated by underscores, no spaces allowed. For example get_user.php.

Directory name:
All lowercase, separated by underscores, no spaces allowed. Such as model, www.

Function name:
Start with a lowercase letter and be named in camel case, for example: function addBlog().
Same as Java and C++.
Function represents a function, that is, an action, so the verb takes precedence. For example, use editBlog instead of blogEdit.
Due to historical reasons, PHP built-in functions have many styles, such as do_something, something_do, dosomething. The newer functions use doSomething to be consistent with the current mainstream languages.
For example: paser_str, json_encode, substr, fetchAll.
Historical reasons may not be changed, but we can ensure that the new code is rigorous and do not let ourselves become historical reasons.

Function in class:
There is a blank line between the two functions. If you have time, sort the functions alphabetically to avoid too much confusion.
For example:
class BlogModel
{
public function addBlog()
{

}

public function updateBlog()
{

}
}

File comments: The
comment immediately follows the next line of The format follows the requirements of PHPdoc: http://manual.phpdoc.org/HTMLframesConverter/default/phpDocumentor/tutorial_tags.author.pkg.html
/**
* Various businesses of blog: adding, updating
* @author sink
*
*/
class BlogModel
{

}
?>

API note:
Be sure to write the input parameters and output format. Write clearly what is output when it is correct and what is output when it is wrong.
Otherwise, others cannot use it.

Function comments:
Be sure to write the output format. Write clearly what is output when it is correct and what is output when it is wrong.
If the input parameters are complex and contain arrays, and the parameters cannot be clearly understood at a glance, you must write comments on the input parameters.
There can be no blank lines between documentation comments and functions.
If the internal steps of the function are complex, you need to write "inline comments".
For example:
/**
* Update blog
* @param int $id blog_id
* @param array $data array(
"content" => "", //Content
"tags" => ; "", //Tag
"update_time" => "", //Update time
)
* @return bool
*/
public function updateBlog($id,$data)
{
step1 //The first step: asdf
step2 // Step 2: qwer
}

URI:
According to the rfc1034 international standard, underscores "_" are prohibited in domain names, and domain names are not case-sensitive.
For example, http://dl_dir.qq.com/ is an incorrect domain name.
http://bkjia.com is the same as http://VERYHUO.COM.
Therefore, it is preferred to use all lowercase letters in the URI, and the name of GET is lowercase, except for the value of GET.
For example
http://www.google.com/?hl=zh-CN
http://www.google.com/?hl=zh-cn
Non-parameters in URI Whether to use lower case for the abbreviation of proper nouns is controversial and inconclusive.
For example
http://fedoraproject.org/zh_CN/
http://zh.wikipedia.org/zh-cn/
http://code.google.com/intl/zh -CN/
http://www.microsoft.com/en-us/
The language code is a proper noun. ISO stipulates that it must be a minus sign, and it is recommended to use capital letters for regions.
The usage of fedora is very strange. It uses its own zh_CN instead of zh-CN. And it is not recommended to use underscores in URIs.
Wiki uses lowercase letters, Google uses uppercase letters, and Microsoft uses lowercase letters.

Prefer to use the minus sign "-" in the URI instead of underscores, except for the name of GET.
For example
http://example.com/1-2-2
http://example.com/?user_id=123
If you want the user to enter the URI manually, don’t be case sensitive , and lowercase is preferred because it is more convenient for users to input.
The actual situation is: users generally manually enter the domain name instead of the URI because the URI is very long. In this case, does it make sense to lowercase the URI? If you use http://example.com/?userId=123, the variable name can use camel case $userId = $_GET['userId'], which can be compared with Java, C++ To be consistent, the database should also be named in camelCase. To be discussed.

Variables:
All lowercase, separated by underscores, for example: $user_id.
Inconsistent with Java and C++. To be discussed.
The member variables of a class, the formal parameters of a function, and the instantiation of a class into an object all abide by the naming rules of variables.
Reason: URI and database have lowercase convention. The parameters are obtained from $_GET and $_POST and stored in the database, so use lowercase.
PHP built-in variables $_GET and $_POST start with an underscore and are all capitalized. No matter how important a custom variable is, do not start it with an underscore to avoid conflicts with built-in variables in the future.
For example: don’t use $_PUT, $_DELETE.

Constant:
All uppercase, separated by underscores. For example: const MEMCACHE_TTL = 600;

PHP short tag:
Use , do not use the short tag ?>. Because it conflicts with xml and is not conducive to deployment.

Braces-like line breaks:
Braces can be used to occupy a line alone, or braces can be placed on a line with others. This is controversial and inconclusive, and remains to be discussed.
class UserModel
{

}
Support line wrappers:
http://www.php.net/manual/zh/language.oop5.basic.php
http://pear.php.net/manual/en/standards.classdef.php

Excellent content, please click the next page!

  • Total 2 pages:
  • Previous page
  • 1
  • 2
  • Next page

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/363931.htmlTechArticleGeneral principles: 1. Semantic When you see the name, you know the meaning. 2. The general prefix is ​​means whether, get means reading, and set means writing. is is followed first by adjectives rather than nouns, for example...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!