Sharing some standard examples of PHP

小云云
Release: 2023-03-21 17:18:01
Original
1456 people have browsed it

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()
    {

    }
}
Copy after login


File comments:
Comments immediately follow the next line of The format follows the requirements of PHPdoc: http://manual.phpdoc.org/HTMLframesConverter/default/phpDocumentor/tutorial_tags.author.pkg.html

<?php
/**
 * blog的各种业务:添加、更新
 * @author sink
 *
 */
class BlogModel
{

}
?>
Copy after login


API notes:
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 cannot be a blank line between the documentation comment and the function.
If the internal steps of the function are complex, you need to write "inline comments".
For example:

/**
 * 更新blog
 * @param int $id blog_id
 * @param array $data array(
    "content" => "", //内容
    "tags" => "", //标签
    "update_time" => "", //更新时间
 )
  * @return bool
 */
public function updateBlog($id,$data)
{
    step1 //第一步:asdf
    step2 //第二步:qwer
}
Copy after login


URI:
根据rfc1034国际标准的规定,域名中禁止出现下划线“_”,域名不区分大小写。
比如http://dl_dir.qq.com/是错误域名。
http://example.com与http://EXAMPLE.COM相同。
所以优先在URI中使用全小写,GET的name小写,但是GET的值除外。
比如
http://www.google.com/?hl=zh-CN
http://www.google.com/?hl=zh-cn
URI中非参数的专有名词的缩写是否使用小写,有争议无定论。
比如
http://fedoraproject.org/zh_CN/
http://zh.wikipedia.org/zh-cn/
http://code.google.com/intl/zh-CN/
http://www.microsoft.com/en-us/
语言文字代码是专有名词,ISO规定必须是减号,且建议地区使用大写。
fedora的用法很奇怪,使用了自己制造的zh_CN,而不是zh-CN。而且不建议在URI中使用下划线。
wiki用了小写,google用了大写,微软用了小写。

优先在URI中使用减号“-”,而不是下划线,GET的name除外。
比如
http://example.com/1-2-2
http://example.com/?user_id=123
如果希望用户手动输入URI,则不要区分大小写,且优先使用小写,因为用户输入更方便。
实际情况是:用户一般是手动输入域名,而不手动输入URI,因为URI很长。在这种情况下,URI小写是否有意义,如果使用 http://example.com/?userId=123,变量名就可以使用驼峰$userId = $_GET['userId'],就能够和Java、C++保持一致,这样数据库也要驼峰命名。待讨论。讨论结果:使用?user_id=123。

变量:
全小写,下划线分隔,例如:$user_id。
与Java、C++不一致。讨论结果:使用$user_id。
类的成员变量、函数的形参、类实例化成一个对象,都遵守变量的命名规则。
原因:URI、数据库有小写惯例,从$_GET、$_POST中获得参数入库,所以用小写。
PHP内置变量$_GET、$_POST使用下划线开头,全大写。自定义的变量无论多么重要,都不要使用下划线开头,以免将来与内置变量冲突。
比如:不要使用$_PUT、$_DELETE。

常量:
全大写,下划线分隔。例如:const MEMCACHE_TTL = 600;

PHP短标签:
使用,不使用短标签。因为与xml冲突,且不利于部署。

类大括号换行:

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

class UserModel {

}
Copy after login

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

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

function getUser() {

}
Copy after login

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

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

if(!empty($name)){

}
Copy after login

或者

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

}
Copy after login


支持换行者:
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:
}
Copy after login

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

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

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

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

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

$user = array(
    &#39;id&#39; => &#39;123&#39;,
    &#39;name&#39; => &#39;user1&#39;,
    &#39;email&#39; => &#39;a@example.com&#39;,
);
Copy after login

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

$users_id = array(&#39;23&#39;,&#39;12&#39;,&#39;24&#39;);//确定
Copy after login


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

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


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

echo &#39;name is:&#39; . $name . &#39;.&#39; . "\n";
$user = array(
    &#39;id&#39; => &#39;123&#39;,
);
Copy after login


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

if(!empty($name)){
    doSomething();
}
Copy after login

错误:

if(!empty($name))
    doSomething();
Copy after login


回车换行:
使用换行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(&#39;Last Modified:Sat, 30 Oct 2010 13:21:21 GMT&#39;);
Copy after login

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

header(&#39;Cache-Control:max-age=0&#39;);
header(&#39;Cache-Control:private&#39;);
Copy after login


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

header(&#39;Content-Type:application/json; charset=UTF-8&#39;);
header(&#39;Content-Type:application/xml; charset=UTF-8&#39;);
header(&#39;Content-Type:application/xhtml+xml; charset=UTF-8&#39;);
header(&#39;Content-Type:text/plain; charset=UTF-8&#39;);
header(&#39;Content-Type:text/html; charset=UTF-8&#39;);
Copy after login


专有名词大小写:
在类、函数、文件名、目录名等各种地方,不特殊对待专有名词,不采用全大写。讨论结果:使用小写。
原因:专有名词难以界定,比如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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template