SlideShare une entreprise Scribd logo
1  sur  65
PHP 编程规范及技巧
   技术部 kim
什么是 Good Code ?

   1. It works

   2. It keeps working

   3. Any dev can understand why
为什么?
怎么样?

   1. 从现在开始

   2. 区别对待你的项目
具体?

   1. PHP 编程规范 _2012.doc
1. 小项目:功能 > 代码规范
    大项目:代码规范 > 功能


2. 显式的声明类名,例如:
   $app = new $_REQUEST[ACTION];
      可改为:
   switch ($_REQUEST[ACTION]) {
     case 'abcd':
        $app = new abcd();
   }
ip2long 在 32/64 位机子上表现不一致
使用字符串的优点:
a) 省却转换过程
b) 清晰,容易阅读
使用数字的优点:
a) 节省空间
b) 排序快,查询快
防止外部调用
 if (!defined('IN_SYS')) {
     header("HTTP/1.1 404 Not Found");
     die;
 }
使用 SVN/Git 管理自己的代码
   Restful 风格的编程

   认证 ticket , cookie , oauth
   json/xml
   GET 、 POST 、 DELETE 、 PUT
   统一而标准的 URI
   完整的 API 文档
   再复杂的业务逻辑,都可以分解为 CURD
    的组合
   经常统计的数字

   Redis::incr() , Redis::decr()
   我们框架的 MVC

   app – controller
   include - model
对待:旧代码,旧项目,旧 bug

最少修改原则
   文档 /doc 集中放置,设置权限,避免外
    部访问
保持屏幕“干净”,是自己更能 focus 在工作
 区,特别是在显示器很小的情况下。
数据传输用 Json - 即 js 对象
   XSS

   Cookie 加 http-only – 微软提出的
   过滤: strip_tags, htmlspecialchars, htmlentities
   防 SQL 注入

   用 mysql_real_escape_string
   Addslashes 不一定可靠

   不省略单引号和双引号
   SELECT * FROM album_info WHERE
    album_id = ‘123’
   MongoDB 注入
   login.php?username=admin&passwd[$ne]=1

   (int), (string), intval()
   注意每个参数的类型
   Iframe 跨域的 POST ,免刷新

   <iframe name="add_favorite"
    id="add_favorite"
    src="http://www.56.com/domain.html"
    marginwidth="0" marginheight="0"
    frameborder="0" width="0" scrolling="no"
    height="0"></iframe>
   跨域 ajax 使用 jsonp
   delete 和 update 操作都需要 limit 1

   MongoDB 的拓展里面有相应选项
   不要使用 半中文半英文 或者 拼音 的命
    名,例如 ding, cai, huodong
   设置 timezone

   date_default_timezone_set (‘PRC’);
   使用 mktime ,而不是用 strtotime

   integer 在 32 位和 64 位体系结构中长度是不
    同的 . 因此某些函数如 strtotime 的行为会
    不同
   设置 mysql 的 utf8 :

   1. mysql_query("SET NAMES 'utf8'");
   2. mysql_set_charset('utf8', $conn); 建议使用
   3. mysqli_set_charset($conn, 'utf8'); 建议使用
   $_SERVER[‘REQUEST_TIME’] 比 time()
    更快,甚至更精确
   unset 大数组 / 大变量

   特别是在超内存的时候,要分 for while 去
    执行
   include() 和 require() 中使用绝对路径

   require ROOT_DIR."include/class.WordFilter.php";
   strtr 比 str_replace 快

   string strtr ( string $str , string $from , string
    $to )
   不使用纯函数编程

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

   不过度的重用
   “@” - 掩耳盗铃

   不得不用“ @”
   echo $str1, $str2, $str3 更快
   curl vs Http::Get/Post
   If (!function_exists('curl_init')
   可多使用 类常量 const 和 static 方法
“There is only one way to do it, the right way”
-- python
   cookie 的 domain 和 path

   最小化授权,带宽,安全
判断是否 POST :
if ( strtoupper($_SERVER['REQUEST_METHOD']) ==
    'POST‘)
{...}
   永远不嫌多的判断:
   file_exists(), function_exists(), isset(), empty(),
    is_writable(), is_*()
   使用 if (false !== strpos($string, "xxx")) , 而
    不是 if(strpos($string, "xxx"))
   header 后面接 exit 或者 die
善用 array_map ,例如我们经常这么用:
 foreach ($arrs as &$a) {
    $a = trim($a);
 }
     但是,其实我们可以这么用:
 $arr = array_map('trim' , $arr);
   xdebug 依然是强大的性能分析工具
   唯一的 database 连接

   singleton
   MongoDB

   one collection per db
   manual sharding
   用尽量短的 key
   一个程序的起点至关重要

   99% 的情形是,接手你程序的那个人会把
    你的程序改的更烂
   不要暴露任何接口的特征,比如拓展名
    /api/abc.php -> /api/abc/
   函数内保持一个,且唯一一个 return
   能不用 global 全局变量的就别使用

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

   $isUserLimit, importDataToTblUser()
   把所有 dirty 的东西集中在一个地方
   Memcached 预热
   兼容所有浏览器的 <a> 标签 onclick 写
    法:
   <a id="abc" href="javascript:void(0);"
    onclick="func(); return false;"></a>
   查询的时候,加了索引还不够,还得
    LIMIT 1 ,特别是你确定只有一条,而你
    也只需要一条记录的情况下
   if ... else throw ... 是一个好习惯,至少你知
    道应该在哪里加 log
   配置都写在 配置文件 里面,绝不要写在
    代码中。
   例如 cfg.all.inc.php ,最好只有一个配置文
    件
   URL seo :
    http://site.douban.com/widget/biz_album/784
    2139/photo/1517038635/
   不用的代码请注释掉,并注明 @deprecated
   优先使用 js 原生方法

   document.getElementById 一定比
    jQuery.find('#xxx') 要快
   一句话写 log : file_put_contents($logFile,
    $logContent, FILE_APPEND);
   每一个数据结构和索引的设计,都要和主
    管上级一起决定

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

   存在即合理
   单例 singleton 模式的应用,适合 file/db/
    cache 等等。

   经验:评论顶踩
   如何提高编程技巧?怎么开始?

     从当前你接触到的代码开始,从每一个细
    节开始,例如你手上的一个 bug ,一个函数
    。
   通过反复的修改,反复的优化,才能有所
    提升。
谢谢

Contenu connexe

Tendances

Jni攻略之十一――启动虚拟机调用Java类
Jni攻略之十一――启动虚拟机调用Java类Jni攻略之十一――启动虚拟机调用Java类
Jni攻略之十一――启动虚拟机调用Java类yiditushe
 
Python xmlrpc-odoo
Python xmlrpc-odooPython xmlrpc-odoo
Python xmlrpc-odoorobin yang
 
由一个简单的程序谈起――之二
由一个简单的程序谈起――之二由一个简单的程序谈起――之二
由一个简单的程序谈起――之二yiditushe
 
第十一章解答
第十一章解答第十一章解答
第十一章解答jiannrong
 
Talking about exploit writing
Talking about exploit writingTalking about exploit writing
Talking about exploit writingsbha0909
 
第五章解答
第五章解答第五章解答
第五章解答jiannrong
 
Free Marker中文文档
Free Marker中文文档Free Marker中文文档
Free Marker中文文档yiditushe
 
第六章解答
第六章解答第六章解答
第六章解答jiannrong
 
恶意网页分析实战
恶意网页分析实战恶意网页分析实战
恶意网页分析实战Huang Toby
 
Mybatis学习培训
Mybatis学习培训Mybatis学习培训
Mybatis学习培训flynofry
 
JavaScript 教程
JavaScript 教程JavaScript 教程
JavaScript 教程Bobby Zhou
 
JavaScript 脚本控件(二)
JavaScript 脚本控件(二)JavaScript 脚本控件(二)
JavaScript 脚本控件(二)RANK LIU
 
MongoDB Basics and Tutorial
MongoDB Basics and TutorialMongoDB Basics and Tutorial
MongoDB Basics and TutorialHo Kim
 
希望科技研发部变量命名及编码规范
希望科技研发部变量命名及编码规范希望科技研发部变量命名及编码规范
希望科技研发部变量命名及编码规范Hongjian Wang
 
BASH 漏洞深入探討
BASH 漏洞深入探討BASH 漏洞深入探討
BASH 漏洞深入探討Tim Hsu
 
Mongo db技术交流
Mongo db技术交流Mongo db技术交流
Mongo db技术交流liuts
 
Php More
Php MorePhp More
Php Morehenbo
 
180518 ntut js and node
180518 ntut js and node180518 ntut js and node
180518 ntut js and nodePeter Yi
 

Tendances (20)

Jni攻略之十一――启动虚拟机调用Java类
Jni攻略之十一――启动虚拟机调用Java类Jni攻略之十一――启动虚拟机调用Java类
Jni攻略之十一――启动虚拟机调用Java类
 
MySQL aio
MySQL aioMySQL aio
MySQL aio
 
Python xmlrpc-odoo
Python xmlrpc-odooPython xmlrpc-odoo
Python xmlrpc-odoo
 
由一个简单的程序谈起――之二
由一个简单的程序谈起――之二由一个简单的程序谈起――之二
由一个简单的程序谈起――之二
 
第十一章解答
第十一章解答第十一章解答
第十一章解答
 
Talking about exploit writing
Talking about exploit writingTalking about exploit writing
Talking about exploit writing
 
第五章解答
第五章解答第五章解答
第五章解答
 
Free Marker中文文档
Free Marker中文文档Free Marker中文文档
Free Marker中文文档
 
第六章解答
第六章解答第六章解答
第六章解答
 
Json知识分享
Json知识分享Json知识分享
Json知识分享
 
恶意网页分析实战
恶意网页分析实战恶意网页分析实战
恶意网页分析实战
 
Mybatis学习培训
Mybatis学习培训Mybatis学习培训
Mybatis学习培训
 
JavaScript 教程
JavaScript 教程JavaScript 教程
JavaScript 教程
 
JavaScript 脚本控件(二)
JavaScript 脚本控件(二)JavaScript 脚本控件(二)
JavaScript 脚本控件(二)
 
MongoDB Basics and Tutorial
MongoDB Basics and TutorialMongoDB Basics and Tutorial
MongoDB Basics and Tutorial
 
希望科技研发部变量命名及编码规范
希望科技研发部变量命名及编码规范希望科技研发部变量命名及编码规范
希望科技研发部变量命名及编码规范
 
BASH 漏洞深入探討
BASH 漏洞深入探討BASH 漏洞深入探討
BASH 漏洞深入探討
 
Mongo db技术交流
Mongo db技术交流Mongo db技术交流
Mongo db技术交流
 
Php More
Php MorePhp More
Php More
 
180518 ntut js and node
180518 ntut js and node180518 ntut js and node
180518 ntut js and node
 

En vedette

Web Caching Architecture and Design
Web Caching Architecture and DesignWeb Caching Architecture and Design
Web Caching Architecture and DesignHo Kim
 
Web UI performance tuning
Web UI performance tuningWeb UI performance tuning
Web UI performance tuningAndy Pemberton
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code ReviewDamien Seguy
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizenVytautas Butkus
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Damien Seguy
 
Coding Best practices (PHP)
Coding Best practices (PHP)Coding Best practices (PHP)
Coding Best practices (PHP)Christian Baune
 
Modular & Event driven UI Architecture
Modular & Event driven UI ArchitectureModular & Event driven UI Architecture
Modular & Event driven UI ArchitectureVytautas Butkus
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code ReviewMilan Vukoje
 
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...Rouven Weßling
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesSiarhei Barysiuk
 
Modern Static Code Analysis in PHP
Modern Static Code Analysis in PHPModern Static Code Analysis in PHP
Modern Static Code Analysis in PHPVladimir Reznichenko
 
Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy CodeAdam Culp
 
Component Based UI Architecture - Alex Moldovan
Component Based UI Architecture - Alex MoldovanComponent Based UI Architecture - Alex Moldovan
Component Based UI Architecture - Alex MoldovanITCamp
 
Modern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentModern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentSuresh Patidar
 
Code review guidelines
Code review guidelinesCode review guidelines
Code review guidelinesLalit Kale
 
UI Architecture & Web Performance
UI Architecture & Web PerformanceUI Architecture & Web Performance
UI Architecture & Web PerformanceKyle Simpson
 
Selenium Architecture
Selenium ArchitectureSelenium Architecture
Selenium Architecturerohitnayak
 
Content Design, UI Architecture and Content-UI-Mapping
Content Design, UI Architecture and Content-UI-MappingContent Design, UI Architecture and Content-UI-Mapping
Content Design, UI Architecture and Content-UI-MappingWolfram Nagel
 

En vedette (20)

Web Caching Architecture and Design
Web Caching Architecture and DesignWeb Caching Architecture and Design
Web Caching Architecture and Design
 
Web UI performance tuning
Web UI performance tuningWeb UI performance tuning
Web UI performance tuning
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code Review
 
Coding standards php
Coding standards phpCoding standards php
Coding standards php
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizen
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
 
Coding Best practices (PHP)
Coding Best practices (PHP)Coding Best practices (PHP)
Coding Best practices (PHP)
 
Modular & Event driven UI Architecture
Modular & Event driven UI ArchitectureModular & Event driven UI Architecture
Modular & Event driven UI Architecture
 
PHP CODING STANDARDS
PHP CODING STANDARDSPHP CODING STANDARDS
PHP CODING STANDARDS
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code Review
 
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
Modern Static Code Analysis in PHP
Modern Static Code Analysis in PHPModern Static Code Analysis in PHP
Modern Static Code Analysis in PHP
 
Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy Code
 
Component Based UI Architecture - Alex Moldovan
Component Based UI Architecture - Alex MoldovanComponent Based UI Architecture - Alex Moldovan
Component Based UI Architecture - Alex Moldovan
 
Modern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentModern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web Development
 
Code review guidelines
Code review guidelinesCode review guidelines
Code review guidelines
 
UI Architecture & Web Performance
UI Architecture & Web PerformanceUI Architecture & Web Performance
UI Architecture & Web Performance
 
Selenium Architecture
Selenium ArchitectureSelenium Architecture
Selenium Architecture
 
Content Design, UI Architecture and Content-UI-Mapping
Content Design, UI Architecture and Content-UI-MappingContent Design, UI Architecture and Content-UI-Mapping
Content Design, UI Architecture and Content-UI-Mapping
 

Similaire à PHP Coding Standard and 50+ Programming Skills

Php应用程序常见安全问题解析
Php应用程序常见安全问题解析Php应用程序常见安全问题解析
Php应用程序常见安全问题解析mysqlops
 
Ria的强力后盾:rest+海量存储
Ria的强力后盾:rest+海量存储 Ria的强力后盾:rest+海量存储
Ria的强力后盾:rest+海量存储 zhen chen
 
PHP & MySQL 教學
PHP & MySQL 教學PHP & MySQL 教學
PHP & MySQL 教學Bo-Yi Wu
 
高性能LAMP程序设计
高性能LAMP程序设计高性能LAMP程序设计
高性能LAMP程序设计fuchaoqun
 
Lamp高性能设计
Lamp高性能设计Lamp高性能设计
Lamp高性能设计锐 张
 
網站設計100步
網站設計100步網站設計100步
網站設計100步evercislide
 
J2ee经典学习笔记
J2ee经典学习笔记J2ee经典学习笔记
J2ee经典学习笔记yiditushe
 
學好 node.js 不可不知的事
學好 node.js 不可不知的事學好 node.js 不可不知的事
學好 node.js 不可不知的事Ben Lue
 
JavaScript Advanced Skill
JavaScript Advanced SkillJavaScript Advanced Skill
JavaScript Advanced Skillfirestoke
 
JavaScript 80+ Programming and Optimization Skills
JavaScript 80+ Programming and Optimization SkillsJavaScript 80+ Programming and Optimization Skills
JavaScript 80+ Programming and Optimization SkillsHo Kim
 
互联网创业服务器运维工具集
互联网创业服务器运维工具集互联网创业服务器运维工具集
互联网创业服务器运维工具集zhen chen
 
MongoDB for C# developer
MongoDB for C# developerMongoDB for C# developer
MongoDB for C# developerdianming.song
 
Erlang Practice
Erlang PracticeErlang Practice
Erlang Practicelitaocheng
 
Kissy design
Kissy designKissy design
Kissy designyiming he
 
HITCON CTF 2014 BambooFox 解題心得分享
HITCON CTF 2014 BambooFox 解題心得分享HITCON CTF 2014 BambooFox 解題心得分享
HITCON CTF 2014 BambooFox 解題心得分享Chong-Kuan Chen
 
KISSY for starter
KISSY for starterKISSY for starter
KISSY for starteryiming he
 

Similaire à PHP Coding Standard and 50+ Programming Skills (20)

Php应用程序常见安全问题解析
Php应用程序常见安全问题解析Php应用程序常见安全问题解析
Php应用程序常见安全问题解析
 
Ria的强力后盾:rest+海量存储
Ria的强力后盾:rest+海量存储 Ria的强力后盾:rest+海量存储
Ria的强力后盾:rest+海量存储
 
Php
PhpPhp
Php
 
PHP & MySQL 教學
PHP & MySQL 教學PHP & MySQL 教學
PHP & MySQL 教學
 
高性能LAMP程序设计
高性能LAMP程序设计高性能LAMP程序设计
高性能LAMP程序设计
 
Lamp高性能设计
Lamp高性能设计Lamp高性能设计
Lamp高性能设计
 
網站設計100步
網站設計100步網站設計100步
網站設計100步
 
J2ee经典学习笔记
J2ee经典学习笔记J2ee经典学习笔记
J2ee经典学习笔记
 
學好 node.js 不可不知的事
學好 node.js 不可不知的事學好 node.js 不可不知的事
學好 node.js 不可不知的事
 
JavaScript Advanced Skill
JavaScript Advanced SkillJavaScript Advanced Skill
JavaScript Advanced Skill
 
JavaScript 80+ Programming and Optimization Skills
JavaScript 80+ Programming and Optimization SkillsJavaScript 80+ Programming and Optimization Skills
JavaScript 80+ Programming and Optimization Skills
 
互联网创业服务器运维工具集
互联网创业服务器运维工具集互联网创业服务器运维工具集
互联网创业服务器运维工具集
 
Js培训
Js培训Js培训
Js培训
 
Hadoop ecosystem
Hadoop ecosystemHadoop ecosystem
Hadoop ecosystem
 
MongoDB for C# developer
MongoDB for C# developerMongoDB for C# developer
MongoDB for C# developer
 
Erlang Practice
Erlang PracticeErlang Practice
Erlang Practice
 
Kissy design
Kissy designKissy design
Kissy design
 
HITCON CTF 2014 BambooFox 解題心得分享
HITCON CTF 2014 BambooFox 解題心得分享HITCON CTF 2014 BambooFox 解題心得分享
HITCON CTF 2014 BambooFox 解題心得分享
 
Optimzing mysql
Optimzing mysqlOptimzing mysql
Optimzing mysql
 
KISSY for starter
KISSY for starterKISSY for starter
KISSY for starter
 

Plus de Ho Kim

解决Lvs上行丢包的过程和收获
解决Lvs上行丢包的过程和收获解决Lvs上行丢包的过程和收获
解决Lvs上行丢包的过程和收获Ho Kim
 
40 Powerful Shortcuts of Xcode 6.x
40 Powerful Shortcuts of Xcode 6.x40 Powerful Shortcuts of Xcode 6.x
40 Powerful Shortcuts of Xcode 6.xHo Kim
 
Project Management Using Redmine
Project Management Using RedmineProject Management Using Redmine
Project Management Using RedmineHo Kim
 
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tipsOpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tipsHo Kim
 
Lua 30+ Programming Skills and 20+ Optimization Tips
Lua 30+ Programming Skills and 20+ Optimization TipsLua 30+ Programming Skills and 20+ Optimization Tips
Lua 30+ Programming Skills and 20+ Optimization TipsHo Kim
 
人人-56 账号拆分项目总结
人人-56 账号拆分项目总结人人-56 账号拆分项目总结
人人-56 账号拆分项目总结Ho Kim
 
OpenResty/Lua Practical Experience
OpenResty/Lua Practical ExperienceOpenResty/Lua Practical Experience
OpenResty/Lua Practical ExperienceHo Kim
 
Character Encoding and Database Transcoding Project
Character Encoding and Database Transcoding ProjectCharacter Encoding and Database Transcoding Project
Character Encoding and Database Transcoding ProjectHo Kim
 
Video Upload Architecture of 56.com
Video Upload Architecture of 56.comVideo Upload Architecture of 56.com
Video Upload Architecture of 56.comHo Kim
 
PHP Optimization for Millions Visits Level
PHP Optimization for Millions Visits LevelPHP Optimization for Millions Visits Level
PHP Optimization for Millions Visits LevelHo Kim
 
Comment System of 56.com
Comment System of 56.comComment System of 56.com
Comment System of 56.comHo Kim
 
Git Essence Tutorial
Git Essence TutorialGit Essence Tutorial
Git Essence TutorialHo Kim
 

Plus de Ho Kim (12)

解决Lvs上行丢包的过程和收获
解决Lvs上行丢包的过程和收获解决Lvs上行丢包的过程和收获
解决Lvs上行丢包的过程和收获
 
40 Powerful Shortcuts of Xcode 6.x
40 Powerful Shortcuts of Xcode 6.x40 Powerful Shortcuts of Xcode 6.x
40 Powerful Shortcuts of Xcode 6.x
 
Project Management Using Redmine
Project Management Using RedmineProject Management Using Redmine
Project Management Using Redmine
 
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tipsOpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
 
Lua 30+ Programming Skills and 20+ Optimization Tips
Lua 30+ Programming Skills and 20+ Optimization TipsLua 30+ Programming Skills and 20+ Optimization Tips
Lua 30+ Programming Skills and 20+ Optimization Tips
 
人人-56 账号拆分项目总结
人人-56 账号拆分项目总结人人-56 账号拆分项目总结
人人-56 账号拆分项目总结
 
OpenResty/Lua Practical Experience
OpenResty/Lua Practical ExperienceOpenResty/Lua Practical Experience
OpenResty/Lua Practical Experience
 
Character Encoding and Database Transcoding Project
Character Encoding and Database Transcoding ProjectCharacter Encoding and Database Transcoding Project
Character Encoding and Database Transcoding Project
 
Video Upload Architecture of 56.com
Video Upload Architecture of 56.comVideo Upload Architecture of 56.com
Video Upload Architecture of 56.com
 
PHP Optimization for Millions Visits Level
PHP Optimization for Millions Visits LevelPHP Optimization for Millions Visits Level
PHP Optimization for Millions Visits Level
 
Comment System of 56.com
Comment System of 56.comComment System of 56.com
Comment System of 56.com
 
Git Essence Tutorial
Git Essence TutorialGit Essence Tutorial
Git Essence Tutorial
 

PHP Coding Standard and 50+ Programming Skills

  • 2. 什么是 Good Code ?  1. It works  2. It keeps working  3. Any dev can understand why
  • 4. 怎么样?  1. 从现在开始  2. 区别对待你的项目
  • 5. 具体?  1. PHP 编程规范 _2012.doc
  • 6. 1. 小项目:功能 > 代码规范 大项目:代码规范 > 功能 2. 显式的声明类名,例如: $app = new $_REQUEST[ACTION]; 可改为: switch ($_REQUEST[ACTION]) { case 'abcd': $app = new abcd(); }
  • 7. ip2long 在 32/64 位机子上表现不一致 使用字符串的优点: a) 省却转换过程 b) 清晰,容易阅读 使用数字的优点: a) 节省空间 b) 排序快,查询快
  • 8. 防止外部调用 if (!defined('IN_SYS')) { header("HTTP/1.1 404 Not Found"); die; }
  • 10. Restful 风格的编程  认证 ticket , cookie , oauth  json/xml  GET 、 POST 、 DELETE 、 PUT  统一而标准的 URI  完整的 API 文档
  • 11. 再复杂的业务逻辑,都可以分解为 CURD 的组合
  • 12. 经常统计的数字  Redis::incr() , Redis::decr()
  • 13. 我们框架的 MVC  app – controller  include - model
  • 15. 文档 /doc 集中放置,设置权限,避免外 部访问
  • 16. 保持屏幕“干净”,是自己更能 focus 在工作 区,特别是在显示器很小的情况下。
  • 17. 数据传输用 Json - 即 js 对象
  • 18. XSS  Cookie 加 http-only – 微软提出的  过滤: strip_tags, htmlspecialchars, htmlentities
  • 19. 防 SQL 注入  用 mysql_real_escape_string  Addslashes 不一定可靠  不省略单引号和双引号  SELECT * FROM album_info WHERE album_id = ‘123’
  • 20. MongoDB 注入  login.php?username=admin&passwd[$ne]=1  (int), (string), intval()  注意每个参数的类型
  • 21. Iframe 跨域的 POST ,免刷新  <iframe name="add_favorite" id="add_favorite" src="http://www.56.com/domain.html" marginwidth="0" marginheight="0" frameborder="0" width="0" scrolling="no" height="0"></iframe>
  • 22. 跨域 ajax 使用 jsonp
  • 23. delete 和 update 操作都需要 limit 1  MongoDB 的拓展里面有相应选项
  • 24. 不要使用 半中文半英文 或者 拼音 的命 名,例如 ding, cai, huodong
  • 25. 设置 timezone  date_default_timezone_set (‘PRC’);
  • 26. 使用 mktime ,而不是用 strtotime  integer 在 32 位和 64 位体系结构中长度是不 同的 . 因此某些函数如 strtotime 的行为会 不同
  • 27. 设置 mysql 的 utf8 :  1. mysql_query("SET NAMES 'utf8'");  2. mysql_set_charset('utf8', $conn); 建议使用  3. mysqli_set_charset($conn, 'utf8'); 建议使用
  • 28. $_SERVER[‘REQUEST_TIME’] 比 time() 更快,甚至更精确
  • 29. unset 大数组 / 大变量  特别是在超内存的时候,要分 for while 去 执行
  • 30. include() 和 require() 中使用绝对路径  require ROOT_DIR."include/class.WordFilter.php";
  • 31. strtr 比 str_replace 快  string strtr ( string $str , string $from , string $to )
  • 32. 不使用纯函数编程  不使用复杂的 OOP ,简单的面向对象  不过度的重用
  • 33. “@” - 掩耳盗铃  不得不用“ @”
  • 34. echo $str1, $str2, $str3 更快
  • 35. curl vs Http::Get/Post  If (!function_exists('curl_init')
  • 36. 可多使用 类常量 const 和 static 方法
  • 37. “There is only one way to do it, the right way” -- python
  • 38. cookie 的 domain 和 path  最小化授权,带宽,安全
  • 39. 判断是否 POST : if ( strtoupper($_SERVER['REQUEST_METHOD']) == 'POST‘) {...}
  • 40. 永远不嫌多的判断:  file_exists(), function_exists(), isset(), empty(), is_writable(), is_*()
  • 41. 使用 if (false !== strpos($string, "xxx")) , 而 不是 if(strpos($string, "xxx"))
  • 42. header 后面接 exit 或者 die
  • 43. 善用 array_map ,例如我们经常这么用: foreach ($arrs as &$a) { $a = trim($a); } 但是,其实我们可以这么用: $arr = array_map('trim' , $arr);
  • 44. xdebug 依然是强大的性能分析工具
  • 45. 唯一的 database 连接  singleton
  • 46. MongoDB  one collection per db  manual sharding  用尽量短的 key
  • 47. 一个程序的起点至关重要  99% 的情形是,接手你程序的那个人会把 你的程序改的更烂
  • 48. 不要暴露任何接口的特征,比如拓展名 /api/abc.php -> /api/abc/
  • 49. 函数内保持一个,且唯一一个 return
  • 50. 能不用 global 全局变量的就别使用  global vs $GLOBALS
  • 51. 变量名,类名,函数名,方法名 都要描述 清楚这是做什么的,比如  $isUserLimit, importDataToTblUser()
  • 52. 把所有 dirty 的东西集中在一个地方
  • 53. Memcached 预热
  • 54. 兼容所有浏览器的 <a> 标签 onclick 写 法:  <a id="abc" href="javascript:void(0);" onclick="func(); return false;"></a>
  • 55. 查询的时候,加了索引还不够,还得 LIMIT 1 ,特别是你确定只有一条,而你 也只需要一条记录的情况下
  • 56. if ... else throw ... 是一个好习惯,至少你知 道应该在哪里加 log
  • 57. 配置都写在 配置文件 里面,绝不要写在 代码中。  例如 cfg.all.inc.php ,最好只有一个配置文 件
  • 58. URL seo : http://site.douban.com/widget/biz_album/784 2139/photo/1517038635/
  • 59. 不用的代码请注释掉,并注明 @deprecated
  • 60. 优先使用 js 原生方法  document.getElementById 一定比 jQuery.find('#xxx') 要快
  • 61. 一句话写 log : file_put_contents($logFile, $logContent, FILE_APPEND);
  • 62. 每一个数据结构和索引的设计,都要和主 管上级一起决定  对待缓存必须仔细,小心,谨慎  存在即合理
  • 63. 单例 singleton 模式的应用,适合 file/db/ cache 等等。  经验:评论顶踩
  • 64. 如何提高编程技巧?怎么开始? 从当前你接触到的代码开始,从每一个细 节开始,例如你手上的一个 bug ,一个函数 。  通过反复的修改,反复的优化,才能有所 提升。