文档章节

Top 11 Best Practices for PHP Development

Amamatthew
 Amamatthew
发布于 2014/08/26 14:11
字数 1124
阅读 8
收藏 0

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.


本文转载自:http://www.phpbuilder.com/articles/application-architecture/optimization/explore-the-top-11-php-b...

上一篇: PHP入门
Amamatthew
粉丝 67
博文 1050
码字总数 76443
作品 0
厦门
后端工程师
私信 提问
Announcing Visual Studio and Kubernetes – Visual S

Announcing Visual Studio and Kubernetes – Visual S Scott Hanselman's Blog2017-11-151 阅读 studio I've been having all kinds of fun lately with Kubernetes , exploring building m......

Scott Hanselman's Blog
2017/11/15
0
0
转载 James Bach提倡的Context-Driven Testing Principles

今天阅读了一篇很好的测试文章,是由测试大师James Bach撰写的。阅读了这篇文章之后,我有一种恍然大悟的感觉,原来好的测试应该是这样的! Context-Driven Testing可以说是James Bach推荐的...

pumpkinmum
2013/03/31
211
0
What Does Agile Really Mean?

What's the Buzz Around "Agile?" If you've set foot in the world of software you've probably heard the word "Agile" more times than you can count. You may have heard this word as......

Bria Grangard
2017/12/25
0
0
Executive Insights on the Current and Future State of Microservices

This article is featured in the new DZone Guide to Microservices. Get your free copy for more insightful articles, industry statistics, and more! To gather insights on the state......

Tom Smith
2017/12/22
0
0
Only 34% of Companies Use Automation Tools to Perform Database Changes, Survey Shows

New global survey of 200+ IT professionals reveals that while more than half of companies have adopted continuous delivery in Application Development, only one in three companie......

Yaniv Yehuda
2017/12/19
0
0

没有更多内容

加载失败,请刷新页面

加载更多

Netty整合Protobuffer

现在我们都知道,rpc的三要素:IO模型,线程模型,然后就是数据交互模型,即我们说的序列化和反序列化,现在我们来看一下压缩比率最大的二进制序列化方式——Protobuffer,而且该方式是可以跨...

算法之名
34分钟前
17
0
如何用C++实现栈

栈的定义 栈(stack)又名堆栈,它是一种运算受限的线性表。限定仅在表尾进行插入和删除操作的线性表。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压...

BWH_Steven
52分钟前
5
0
编程作业20190210900169

1编写一个程序,提示用户输入名和姓,然后以“名,姓”的格式打印出来。 #include <stdio.h>#include <stdlib.h> int main(){ char firstName[20]; char lastName[20]; print......

1李嘉焘1
今天
12
0
补码的优点及原理分析

只讨论整数 1.计算机内部为什么没有减法器? 减法运算本身其实就是加法,如x - y即x +(-y),所以只需要将负数成功表示出来并可以参加加法运算,那加法器就可同时实现“+”和“-”的运算。这...

清自以敬
今天
76
0
Docker 可视化管理 portainer

官网安装指南: https://portainer.readthedocs.io/en/latest/deployment.html docker-compose.yml 位置,下载地址:https://downloads.portainer.io/docker-compose.yml...

Moks角木
今天
9
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部