php coding standard and skills

65
PHP PHP 编编编编编编编 编编编编编编编 技技技 技技技 kim kim

Upload: ho-kim

Post on 15-Jan-2015

1.558 views

Category:

Technology


7 download

DESCRIPTION

PHP Coding Standard and Skills

TRANSCRIPT

Page 1: PHP Coding Standard and Skills

PHPPHP 编程规范及技巧编程规范及技巧技术部 技术部 kimkim

Page 2: PHP Coding Standard and Skills

什么是什么是 Good CodeGood Code ??

1. It works1. It works

2. It keeps working2. It keeps working

3. Any dev can understand why3. Any dev can understand why

Page 3: PHP Coding Standard and Skills

为什么?为什么?

Page 4: PHP Coding Standard and Skills

怎么样?怎么样?

1. 1. 从现在开始从现在开始

2. 2. 区别对待你的项目区别对待你的项目

Page 5: PHP Coding Standard and Skills

具体?具体?

1. PHP1. PHP 编程规范编程规范 _2012.doc_2012.doc

Page 6: PHP Coding Standard and Skills

1. 1. 小项目:功能 小项目:功能 > > 代码规范代码规范 大项目:代码规范 大项目:代码规范 > > 功能功能

2. 2. 显式的声明类名,例如:显式的声明类名,例如: $app = new $_REQUEST[ACTION];$app = new $_REQUEST[ACTION]; 可改为:可改为: switch ($_REQUEST[ACTION]) {switch ($_REQUEST[ACTION]) { case 'abcd':case 'abcd': $app = new abcd();$app = new abcd(); }}

Page 7: PHP Coding Standard and Skills

ip2long ip2long 在 在 32/64 32/64 位机子上表现不一致位机子上表现不一致使用字符串的优点:使用字符串的优点:a) a) 省却转换过程省却转换过程b) b) 清晰,容易阅读清晰,容易阅读使用数字的优点:使用数字的优点:a) a) 节省空间节省空间b) b) 排序快,查询快排序快,查询快

Page 8: PHP Coding Standard and Skills

防止外部调用防止外部调用 if (!defined('IN_SYS')) {if (!defined('IN_SYS')) {

header("HTTP/1.1 404 Not header("HTTP/1.1 404 Not Found");Found");

die;die;

}}

Page 9: PHP Coding Standard and Skills

使用 使用 SVN/Git SVN/Git 管理自己的代码管理自己的代码

Page 10: PHP Coding Standard and Skills

Restful Restful 风格的编程风格的编程

认证 认证 ticketticket ,, cookiecookie ,, oauthoauth json/xmljson/xml GETGET 、、 POSTPOST 、、 DELETEDELETE 、、 PUTPUT 统一而标准的 统一而标准的 URIURI 完整的 完整的 API API 文档文档

Page 11: PHP Coding Standard and Skills

再复杂的业务逻辑,都可以分解为 再复杂的业务逻辑,都可以分解为 CURD CURD 的组合的组合

Page 12: PHP Coding Standard and Skills

经常统计的数字经常统计的数字

Redis::incr() , Redis::decr()Redis::incr() , Redis::decr()

Page 13: PHP Coding Standard and Skills

我们框架的我们框架的 MVCMVC

app app –– controller controller include - modelinclude - model

Page 14: PHP Coding Standard and Skills

对待:旧代码,旧项目,旧对待:旧代码,旧项目,旧 bug bug

最少修改原则最少修改原则

Page 15: PHP Coding Standard and Skills

文档 文档 /doc /doc 集中放置,设置权限,避免外集中放置,设置权限,避免外部访问部访问

Page 16: PHP Coding Standard and Skills

保持屏幕保持屏幕““干净干净””,是自己更能,是自己更能 focusfocus 在工在工作区,特别是在显示器很小的情况下。作区,特别是在显示器很小的情况下。

Page 17: PHP Coding Standard and Skills

数据传输用数据传输用 Json - Json - 即 即 js js 对象对象

Page 18: PHP Coding Standard and Skills

XSSXSS

Cookie Cookie 加 加 http-only http-only –– 微软提出的微软提出的 过滤:过滤: strip_tags, htmlspecialchars, strip_tags, htmlspecialchars,

htmlentitieshtmlentities

Page 19: PHP Coding Standard and Skills

防防 SQLSQL 注入注入

用 用 mysql_real_escape_string mysql_real_escape_string Addslashes Addslashes 不一定可靠不一定可靠

不省略单引号和双引号不省略单引号和双引号 SELECT * FROM album_info SELECT * FROM album_info

WHERE album_id = WHERE album_id = ‘‘123123’’

Page 20: PHP Coding Standard and Skills

MongoDB MongoDB 注入注入 login.php?login.php?

username=admin&passwd[$ne]=1 username=admin&passwd[$ne]=1

(int), (string), intval() (int), (string), intval() 注意每个参数的类型注意每个参数的类型

Page 21: PHP Coding Standard and Skills

Iframe Iframe 跨域的 跨域的 POST POST ,免刷新,免刷新

<iframe name="add_favorite" <iframe name="add_favorite" id="add_favorite" id="add_favorite" src="http://www.56.com/domain.htsrc="http://www.56.com/domain.html" marginwidth="0" ml" marginwidth="0" marginheight="0" frameborder="0" marginheight="0" frameborder="0" width="0" scrolling="no" width="0" scrolling="no" height="0"></iframe>height="0"></iframe>

Page 22: PHP Coding Standard and Skills

跨域 跨域 ajax ajax 使用 使用 jsonp jsonp

Page 23: PHP Coding Standard and Skills

delete delete 和 和 update update 操作都需要 操作都需要 limit 1limit 1

MongoDB MongoDB 的拓展里面有相应选项的拓展里面有相应选项

Page 24: PHP Coding Standard and Skills

不要使用 半中文半英文 或者 拼音 的命名,不要使用 半中文半英文 或者 拼音 的命名,例如 例如 ding, cai, huodongding, cai, huodong

Page 25: PHP Coding Standard and Skills

设置 设置 timezone timezone

date_default_timezone_set (date_default_timezone_set (‘‘PRCPRC’’););

Page 26: PHP Coding Standard and Skills

使用 使用 mktime mktime ,而不是用 ,而不是用 strtotimestrtotime

integerinteger 在在 3232 位和位和 6464 位体系结构中长度位体系结构中长度是不同的是不同的 . . 因此某些函数如 因此某些函数如 strtotime strtotime 的的行为会不同行为会不同

Page 27: PHP Coding Standard and Skills

设置 设置 mysql mysql 的 的 utf8 :utf8 :

1. mysql_query("SET NAMES 1. mysql_query("SET NAMES 'utf8'");'utf8'");

2. mysql_set_charset('utf8', $conn); 2. mysql_set_charset('utf8', $conn); 建议使用建议使用

3. mysqli_set_charset($conn, 'utf8'); 3. mysqli_set_charset($conn, 'utf8'); 建议使用建议使用

Page 28: PHP Coding Standard and Skills

$_SERVER[$_SERVER[‘‘REQUEST_TIMEREQUEST_TIME’’] ] 比 比 time() time() 更快,甚至更精确更快,甚至更精确

Page 29: PHP Coding Standard and Skills

unset unset 大数组大数组 // 大变量大变量

特别是在超内存的时候,要分 特别是在超内存的时候,要分 for while for while 去执行去执行

Page 30: PHP Coding Standard and Skills

include() include() 和 和 require() require() 中使用绝对路径中使用绝对路径

require require ROOT_DIR."include/class.WordFilter.php";ROOT_DIR."include/class.WordFilter.php";

Page 31: PHP Coding Standard and Skills

strtr strtr 比 比 str_replace str_replace 快快

string strtr ( string $str , string string strtr ( string $str , string $from , string $to )$from , string $to )

Page 32: PHP Coding Standard and Skills

不使用纯函数编程不使用纯函数编程

不使用复杂的 不使用复杂的 OOPOOP ,简单的面向对象,简单的面向对象

不过度的重用不过度的重用

Page 33: PHP Coding Standard and Skills

““@@”” - - 掩耳盗铃掩耳盗铃

不得不用不得不用““ @@””

Page 34: PHP Coding Standard and Skills

echo $str1, $str2, $str3 echo $str1, $str2, $str3 更快更快

Page 35: PHP Coding Standard and Skills

curl vs Http::Get/Postcurl vs Http::Get/Post If (!function_exists('curl_init')If (!function_exists('curl_init')

Page 36: PHP Coding Standard and Skills

可多使用 类常量 可多使用 类常量 const const 和 和 static static 方法方法

Page 37: PHP Coding Standard and Skills

““There is only one way to do it, the There is only one way to do it, the right wayright way””

-- python-- python

Page 38: PHP Coding Standard and Skills

cookie cookie 的 的 domain domain 和 和 pathpath

最小化授权,带宽,安全最小化授权,带宽,安全

Page 39: PHP Coding Standard and Skills

判断是否 判断是否 POST POST : : if if (( strtoupper($_SERVER['REQUEST_METHOD']) strtoupper($_SERVER['REQUEST_METHOD'])

== 'POST== 'POST‘‘))

{...}{...}

Page 40: PHP Coding Standard and Skills

永远不嫌多的判断: 永远不嫌多的判断: file_exists(), function_exists(), isset(), file_exists(), function_exists(), isset(),

empty(), is_writable(), is_*()empty(), is_writable(), is_*()

Page 41: PHP Coding Standard and Skills

使用 使用 if (false !== strpos($string, if (false !== strpos($string, "xxx")) , "xxx")) , 而不是 而不是 if(strpos($string, if(strpos($string, "xxx"))"xxx"))

Page 42: PHP Coding Standard and Skills

header header 后面接 后面接 exit exit 或者 或者 diedie

Page 43: PHP Coding Standard and Skills

善用 善用 array_map array_map ,例如我们经常这么用:,例如我们经常这么用: foreach ($arrs as &$a) {foreach ($arrs as &$a) {

$a = trim($a);$a = trim($a);

}}

但是,其实我们可以这么用:但是,其实我们可以这么用: $arr = array_map('trim' , $arr);$arr = array_map('trim' , $arr);

Page 44: PHP Coding Standard and Skills

xdebug xdebug 依然是强大的性能分析工具依然是强大的性能分析工具

Page 45: PHP Coding Standard and Skills

唯一的 唯一的 database database 连接连接

singletonsingleton

Page 46: PHP Coding Standard and Skills

MongoDBMongoDB

one collection per dbone collection per db manual shardingmanual sharding 用尽量短的 用尽量短的 keykey

Page 47: PHP Coding Standard and Skills

一个程序的起点至关重要一个程序的起点至关重要

99%99% 的情形是,接手你程序的那个人会把的情形是,接手你程序的那个人会把你的程序改的更烂你的程序改的更烂

Page 48: PHP Coding Standard and Skills

不要暴露任何接口的特征,比如拓展名 不要暴露任何接口的特征,比如拓展名 /api/abc.php -> /api/abc//api/abc.php -> /api/abc/

Page 49: PHP Coding Standard and Skills

函数内保持一个,且唯一一个 函数内保持一个,且唯一一个 returnreturn

Page 50: PHP Coding Standard and Skills

能不用 能不用 global global 全局变量的就别使用全局变量的就别使用

global vs $GLOBALSglobal vs $GLOBALS

Page 51: PHP Coding Standard and Skills

变量名,类名,函数名,方法名 都要描述变量名,类名,函数名,方法名 都要描述清楚这是做什么的,比如清楚这是做什么的,比如

$isUserLimit, $isUserLimit, importDataToTblUser()importDataToTblUser()

Page 52: PHP Coding Standard and Skills

把所有 把所有 dirty dirty 的东西集中在一个地方的东西集中在一个地方

Page 53: PHP Coding Standard and Skills

Memcached Memcached 预热预热

Page 54: PHP Coding Standard and Skills

兼容所有浏览器的 兼容所有浏览器的 <a> <a> 标签 标签 onclick onclick 写写法:法:

<a id="abc" <a id="abc" href="javascript:void(0);" href="javascript:void(0);" onclick="func(); return false;"></a>onclick="func(); return false;"></a>

Page 55: PHP Coding Standard and Skills

查询的时候,加了索引还不够,还得 查询的时候,加了索引还不够,还得 LIMIT 1 LIMIT 1 ,特别是你确定只有一条,而你,特别是你确定只有一条,而你也只需要一条记录的情况下也只需要一条记录的情况下

Page 56: PHP Coding Standard and Skills

if ... else throw ... if ... else throw ... 是一个好习惯,至少是一个好习惯,至少你知道应该在哪里加 你知道应该在哪里加 loglog

Page 57: PHP Coding Standard and Skills

配置都写在 配置文件 里面,绝不要写在代配置都写在 配置文件 里面,绝不要写在代码中。码中。

例如 例如 cfg.all.inc.php cfg.all.inc.php ,最好只有一个配,最好只有一个配置文件置文件

Page 58: PHP Coding Standard and Skills

URL seo URL seo :: http://site.douban.com/widget/biz_http://site.douban.com/widget/biz_album/7842139/photo/1517038635/album/7842139/photo/1517038635/

Page 59: PHP Coding Standard and Skills

不用的代码请注释掉,并注明 不用的代码请注释掉,并注明 @deprecated@deprecated

Page 60: PHP Coding Standard and Skills

优先使用 优先使用 js js 原生方法原生方法

document.getElementById document.getElementById 一定比 一定比 jQuery.find('#xxx') jQuery.find('#xxx') 要快要快

Page 61: PHP Coding Standard and Skills

一句话写 一句话写 log log ::file_put_contents($logFile, file_put_contents($logFile, $logContent, FILE_APPEND);$logContent, FILE_APPEND);

Page 62: PHP Coding Standard and Skills

每一个数据结构和索引的设计,都要和主每一个数据结构和索引的设计,都要和主管上级一起决定管上级一起决定

对待缓存必须仔细,小心,谨慎对待缓存必须仔细,小心,谨慎

存在即合理存在即合理

Page 63: PHP Coding Standard and Skills

单例 单例 singleton singleton 模式的应用,适合 模式的应用,适合 file/db/cache file/db/cache 等等。等等。

经验:评论顶踩经验:评论顶踩

Page 64: PHP Coding Standard and Skills

如何提高编程技巧?怎么开始?如何提高编程技巧?怎么开始?

从当前你接触到的代码开始,从每一个细从当前你接触到的代码开始,从每一个细节开始,例如你手上的一个节开始,例如你手上的一个 bugbug ,一个函,一个函数。数。

通过反复的修改,反复的优化,才能有所通过反复的修改,反复的优化,才能有所提升。提升。

Page 65: PHP Coding Standard and Skills

谢谢谢谢