2019独角兽企业重金招聘Python工程师标准>>>

Right from its inception, PHP was widely used to develop web based applications. Since PHP is a scripting language, one must follow some rules while developing.

This article will discuss the best practices that are generally followed in the PHP world.

1. Error reporting should be turned on

Error reporting is a very useful function in PHP and should be enabled while in the development phase. This helps us to identify the problems in our code. The most commonly used feature is 'E_ALL', which helps us to spot all the warnings and critical errors. It must be noted that before we put our code into production, we should turn off this feature as this would expose all the potential errors on the browser.

       Delivering Application Data On-Demand   Download Now

2. Use the DRY approach

DRY stands for Do not Repeat Yourself'. This concept is a very useful programming concept and should be used in any programming language, such as Java, C# or PHP. Using the DRY approach we ensure that there is no redundant code. A piece of code that violates DRY is referred to as WET solution. WET stands for write everything twic or we enjoy typing. Let us have a look into the following code:

Listing 1: DRY and WET approaches

$mysql  = mysql_connect ( 'localhost',  'mysqladmin_uid', 'mysqladmin_pwd' );
mysql_select_db( 'DB_NAME' ) or die( "Sorry !! No database selected!");

The code above is based on the WET approach as the relevant parameters are hardcoded. Following the DRY approach, the code can be updated to:

$db_host = ' localhost ';
$db_user = ' mysqladmin_uid ';
$db_password = ' mysqladmin_pwd ';
$db_database = ' DB_NAME ';
$mysql = mysql_connect($db_host, $db_user, $db_password);
mysql_select_db($db_database);

3. Indentation and Use of whitespace

While writing code in any programming language, you must ensure that the code is properly indented and sufficient white space is provided wherever required. This increases the readability of the code and helps us to maintain the code in a more efficient manner.

4. Meaningful and consistent naming standards

As in any programming language, PHP experts also advise to follow meaningful naming standards. We have two major approaches while we ensure to implement this:

Using Camel Case– In this approach, the first letter is in lower case and first letter of every word thereafter is in upper case.

Listing 2: Code snippet using camel case

public class MyClass {public void methodName(String argName) {}
}

Using underscores between two words– In this approach, we put an underscore character ('_') between every two words. Using this approach, the code can be modified as follows:

Listing 3: Code snippet using underscores

public class MyClass {
public void method_name(String arg_name) {
}
}

5. Deep Nesting should be avoided

Multilevel nesting reduces the readability of the code regardless of programming language. Any programmer should avoid using deep nesting.

Listing 4: Code snippet having multi level nesting

public class MyClass {
public void method_name(String arg_name) {
if (is_writable($folder)) {if ($fp = fopen($file_location_path,'w')) {if ($stuff = extractSomeConditionalStuff()) {if ( fwrite ( $fp, $stuff) )  {// ...}  else  {return false;}
} else {return false;
}
} else {return false;
}
} else {return false;
}
}
}

The code above is a simple nested code. As we can see it is very difficult to figure which if block ends where. For a better readability, let us modify the code:

Listing 5: Code snippet avoiding multi level nesting

function method_name (String arg_name) {
// ...if (!is_writable($folder)) {return false;}if (!$fp = fopen($file_location_path,'w')) {return false;}if (!$stuff = extractSomeConditionalStuff()) {return false;}if (fwrite($fp, $stuff)) {// ...} else {return false;}
}

6. Use adequate comments

As in any programming language, make sure that your source code has sufficient inline comments. This is a standard practice and should be followed. This helps in further analyzing the code base as it is a often the case that the person who is developing the code is not maintaining the same. Even if the same person is asked to make some changes in the code, inline comments will always be helpful to understand the motive of writing the code. In order to maintain high class comment standard in PHP I would recommend you familiarize yourself with a PHP documentation package such as phpDocumentor.

7. Do not put phpInfo() function in web root

phpInfo() is a very important function and should be used with utmost care. Using this function, anyone can get the details of the server environment. It is always advisable to keep the file containing phpInfo()function in a secured location. Once the development is done, it should be taken out of the code immediately.

8. Never trust the user

If your application involves any user input, write your code in such a way that it can handle all sorts of possible inputs. A good approach to protect your application from hackers is to always initialize your variables with some initial value that may not be relevant in the existing business flow.

9. Use Cache mechanism wherever required

Good programming approaches always suggest using the cache mechanism as the cache helps us to achieve better performance. In the PHP world, caching is achieved using:

Memcached– an in memory key-value pair store used for small chunks of data.

APC– Alternative PHP Cache an open opcode cache for PHP

XCache– A fast reliable PHP opcode cache

Zend Cache– A collection of APIs for realizing advanced caching capabilities.

eAcclerator– Open source caching tool

10. Avoid copying extra variables

It is not a good programming practice to copy predefined variables into local variables having smaller names. This has an adverse effect on the performance of the application. Let us see the following code snippet:

Listing 6: Copying extra variables

$desc = strip_tags($_POST['PHP description']);
echo $desc;

The code snippet above is an example of copying a variable into a local variable unnecessarily. This is not at all a good practice. The same effect can be achieved by using the following code:

echo strip_tags($_POST['PHP description']);

11. Use frameworks

Frameworks are developed after a great deal of research and hence they prove to be less problematic. They make our lives easier as they provide proven solutions. In PHP there are lots of frameworks available. During development, you should make use of these. One of these frameworks that are widely used is MVC or Model View Controller.

Conclusion

• Best practices guide us to develop code in a more efficient manner.

• Following best practices ensures better performance of the application.

• As in other programming language, PHP also follows the best practices in the industry which ensures that the application developed is a good one.

About the Author

Kaushik Pal is a technical architect with 15 years of experience in enterprise application and product development. He has expertise in web technologies, architecture/design, java/j2ee, Open source and big data technologies. You can find more of his work at www.techalpine.com and you can email him here.

转载于:https://my.oschina.net/ajian2014/blog/306730

Top 11 Best Practices for PHP Development相关推荐

  1. @程序员,这 TOP 11 物联网云平台速码!

    今天,我们将看看用于物联网开发的顶级的.最值得推荐的云平台. 作者 | Diksha Rana 译者 | 胡雪蕊,责编 | 郭芮 出品 | CSDN(ID:CSDNnews) 以下为译文: 话不多说, ...

  2. Xcode 11 的那些新东西

    黑客技术 点击右侧关注,了解黑客的世界! Java开发进阶 点击右侧关注,掌握进阶之路! Python开发 点击右侧关注,探讨技术话题! 作者丨知识小集 来源丨知识小集(zsxjtip) Xcode ...

  3. linux java top_linux top命令 监测系统性能

    实时动态地查看系统的整体运行情况,是一个综合了多方信息监测系统性能和运行信息的实用工具. 命令: top [opeartion] iotop iftop top - 11:09:33 up 20:47 ...

  4. 在Ubuntu 18.04系统上安装Java 11的方法

    本文将介绍在Ubuntu 18.04/Ubuntu 16.04/Debian 9系统上安装Java 11的方法,可以通过openjdk-11.0.1_linux-x64_bin.tar.gz.jdk- ...

  5. Linux 的 top 命令平均负载

    每次发现系统变慢时,我们通常做的第一件事就是使用 uptime 或 top命令查看系统的 "平均负载" [root@rocketmq-n2 ~]# uptime11:33:53 u ...

  6. 软件开发 自学_自学11个月内如何获得第一份有薪软件开发人员工作

    软件开发 自学 by Akogwu Uche 通过Akogwu Uche 自学11个月内如何获得第一份有薪软件开发人员工作 (How I got my first paid software deve ...

  7. Linux笔记 No.20---(进程管理工具:ps、pstree、top、pgrep、kill、killall、pkill、查看系统资源的使用vmstat)

    文章目录 一.定时任务crontab实现每秒执行 二.进程 (一)Linux程序与进程 1.程序和进程的区别 2.进程和线程的区别 3.父子进程的关系 三.进程管理工具 (一)ps命令 (二)pstr ...

  8. linux中top界面详解,Linux中top命令输出详解

    前言 Linux下的top命令我相信大家都用过,自从我接触Linux以来就一直用top查看进程的CPU和MEM排行榜.但是top命令的其他输出结果我都没有了解,这些指标都代表什么呢,什么情况下需要关注 ...

  9. 24.Linux进程管理工具——ps,pstree,pgrep,kill,top,htop,vmstat

    1.        ps 显示系统进程瞬间的运行动态的命令ps (1)选项:-A:所有的进程均显示出来,与 -e 具有同样的效果: -a:显示现行终端机下的所有进程,包括其他用户的进程: -u:以用户 ...

最新文章

  1. linux文件操作篇 (一)文件属性与权限
  2. docker部署项目 入门版
  3. 在Linux上安装PostgreSQL
  4. 12v60ah锂电池组装图_锂电池基本参数,结合电动自行车电池应用分析
  5. C/C++求职宝典21个重点笔记(常考笔试面试点)
  6. 教育部计算机科学,关于批准计算机科学与技术专业教学改革与实践项目立项的通知...
  7. __doPostBack用法 【csdn】
  8. 密码登录模式流程分析
  9. java官方 jax rs_jboss7 Java API for RESTful Web Services (JAX-RS) 官方文档
  10. redis——redis持久化处理
  11. 如何获取NuGet以安装/更新packages.config中的所有软件包?
  12. Python 数据结构与算法 —— Prim 算法与小顶堆
  13. JAVA web App扫码登录
  14. 您需要计算机管理员权限,安装需要管理员权限,教您怎么设置安装软件需要管理员权限...
  15. ICT通信运营企业的重建之服务升级(三)----如何打造ICT服务满意度
  16. Oracle数据库 | Oracle备份实例
  17. 常见容错机制:failover、failback、failfast、failsafe
  18. 20190919-6 四则运算试题生成
  19. Peer Pressure(博弈论+机制设计) 论文阅读笔记
  20. UVA, 563 Crimewave

热门文章

  1. 《你当像鸟飞往你的山》
  2. 以WhatsApp为例,外贸人如何从0到1构建社交营销闭环全流程
  3. 百度传课网易云课堂在线教育平台竞品分析【转】
  4. MacOs | 一只捣乱桌面宠物鹅
  5. 海龟交易法则13_系统
  6. 浅谈“戒色”与“慎独”
  7. Java练习题__删除公共字符
  8. html弹性盒子布局,div+css3弹性盒子(flex box)布局
  9. 游戏直播平台新赛程:负重前行与危中求生
  10. 快速解决Android编译报错 : Manifest merger failed with multiple errors, see logs