Home  >  Article  >  Backend Development  >  Sharing some standard examples of PHP

Sharing some standard examples of PHP

小云云
小云云Original
2018-03-19 13:10:511397browse

This article mainly shares with you some standard examples of PHP. Hope it helps everyone. When formulating specifications, please note: Generally, there should be no situation where both are acceptable. For example, both tab and 4 spaces will work, but the result will be confusing code.

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

2. 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, it is getUser
To get multiple users, it is getUsers

4. Redundant suffix
Try not to use data, list, and info suffixes unless there are special circumstances.
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 is difficult 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? Function names ending in adjectives feel inappropriate. To be discussed. Discussion result: getUserBasicInfo is suitable.
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. Discussion results: The current enhancement function is Lib, and plugins and addons will be considered later.

7. Commonly used vocabulary
Use URI first, not URL. Because of more strictness, new naming began to use URI. For example, js's encodeURI, PHP's $_SERVER['REQUEST_URI'].
Deadline and TTL: deadline represents the last moment, and TTL represents the survival time. For example, if the current time is 1310449710 and the TTL is 60 seconds, the deadline is 1310449710 + 60 = 1310449770.

Class name:
Starts with a capital letter and is named in 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:
The same as the class name. This is related to php autoload. In order to autoload, the class name must always be very long. To be discussed. Discussion result: Automatic class loading can also be achieved by complying with camel case.
Same as 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 use 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, 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:
Comments immediately follow the next line of d613854389aa1e54a748d9e719ccb52e,不使用短标签b26da186e11666e6dd99f28d6205715c。因为与xml冲突,且不利于部署。

类大括号换行:

可以采用大括号单独占一行,也可以大括号与别的放在一行,有争议无定论,待讨论。讨论结果:使用“同行”。

class UserModel {

}

支持换行者:
http://www.php.net/manual/zh/language.oop5.basic.php
http://pear.php.net/manual/en/standards.classdef.php

函数大括号换行:
有争议无定论,待讨论。讨论结果:使用“同行”。

function getUser() {

}

支持换行者:
http://www.php.net/manual/zh/language.oop5.basic.php
http://pear.php.net/manual/en/standards.funcdef.php

if大括号换行:
有争议无定论,待讨论。讨论结果:使用“同行”。
例如:

if(!empty($name)){

}

或者

if(!empty($name)) { //确定

}


支持换行者:
http://www.possibility.com/Cpp/CppCodingStandard.html#brace
http://www.php.net/manual/zh/language.oop5.basic.php
http://pear.php.net/manual/en/standards.control.php
switch大括号换行:
讨论结果:使用“同行”。

switch (...) {
    case 1:
        ...
        break;

    default:
}

支持换行者:
http://www.possibility.com/Cpp/CppCodingStandard.html#switch

数组小括号换行:
有争议无定论。讨论结果:使用“同行”。

$user = array(
    "id" => "123",
    "name" => "user1",
    "email" => "a@example.com",
)

支持同行者:
http://pear.php.net/manual/en/standards.arrays.php

数组内部换行:
2维及以上数组的数组内部换行。
如:

$user = array(
    'id' => '123',
    'name' => 'user1',
    'email' => 'a@example.com',
);

1维数组内部不换行。讨论结果:1维数组内部不换行。
如:

$users_id = array('23','12','24');//确定


数组最后的逗号:
数组每一行最后要有逗号,这样方便以后添加。不过前端JSON最后不能有逗号,否则有的浏览器不支持,待讨论。讨论结果:都行,因为后端不用考虑IE前端。
比如

$user = array(
    'id' => '123',
    'name' => 'user1', //都行,优点:大数组,经常添加一行,方便。如果没有逗号,确实太难以添加了。
);
$user = array(
    'id' => '123',
    'name' => 'user1' //都行,优点:严谨,逗号表示分隔,最后一个不需要分隔。
);


单引号与双引号:
优先使用单引号,当需要转义时使用双引号,变量不放在双引号中。这与JSON不同,JSON全是双引号,待讨论。讨论结果:优先使用单引号。
比如:

echo 'name is:' . $name . '.' . "\n";
$user = array(
    'id' => '123',
);


条件判断的大括号:
必须有大括号,即使只有一行。
正确:

if(!empty($name)){
    doSomething();
}

错误:

if(!empty($name))
    doSomething();


回车换行:
使用换行LF(\n,0a,Unix风格)。不使用CR+LF(Windows风格)。
参考:http://zh.wikipedia.org/zh-cn/%E6%8F%9B%E8%A1%8C
eclipse——》workspace——》New text file line delimiter——》Other:Unix

编码:
使用UTF-8 no BOM。不得使用Windows记事本进行保存,因为记事本是UTF-8 BOM CR+LF。
eclipse——》workspace——》Text file encoding——》Other:UTF-8

缩进:
使用4个空格进行缩进,也可以采用tab进行缩进。讨论结果:4个空格。
支持4个空格者://确定
http://www.oracle.com/technetwork/java/codeconventions-136091.html#262

支持2个空格者:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Spaces_vs._Tabs

支持3、4或8个空格者:

http://www.possibility.com/Cpp/CppCodingStandard.html#indent


要保证缩进正确,如果使用4个空格,一定不要出现5个空格或者11个空格。
eclipse——》General——》Editor——》Text Editors——》show whitespace characters
vim ~/.vimrc
set expandtab
set softtabstop=4
set shiftwidth=4
set autoindent

HTTP协议缓存:
文章使用Last Modified表示最后修改时间,不禁止缓存。

header('Last Modified:Sat, 30 Oct 2010 13:21:21 GMT');

需要用户登录的页面,禁止缓存。

header('Cache-Control:max-age=0');
header('Cache-Control:private');


HTTP协议编码与mime:
HTTP输出一定要声明编码与mime。charset与分号之间要有一个空格。小写utf-8还是大写UTF-8,尚未找到文档,待调研。
比如

header('Content-Type:application/json; charset=UTF-8');
header('Content-Type:application/xml; charset=UTF-8');
header('Content-Type:application/xhtml+xml; charset=UTF-8');
header('Content-Type:text/plain; charset=UTF-8');
header('Content-Type:text/html; charset=UTF-8');


专有名词大小写:
在类、函数、文件名、目录名等各种地方,不特殊对待专有名词,不采用全大写。讨论结果:使用小写。
原因:专有名词难以界定,比如HTML、CSS、CRUD。而且全大写导致与驼峰冲突,比如页面助手类,全大写是HTMLHelper,不如HtmlHelper。
支持不特殊处理:
HTML是专有名词,但mime中就使用Content-Type:text/html,而不是text/HTML。
例子:
采用UserDb.php,而不是UserDB.php。

相关推荐:

php规范解析

The above is the detailed content of Sharing some standard examples of PHP. For more information, please follow other related articles on the PHP Chinese website!

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