15 Best Practices of PHP Development for Beginners

commas-left

Do you want to learn some of the best practices of PHP?

Check out this post as it attempts to teach you the best practices of the most widely used programming languages, PHP.

commas-right

php Beginners

PHP was the most widely used for developing web based applications since its inception. As PHP is one of the leading scripting languages, every developers have to follow some rules while development process.

In this post, we will discuss some best practices that usually followed in the PHP world.

Highly recommend to use {C}

Many of the programmers would using shortcuts when declaring PHP. Below given is an example:

1
2
3
4
5
6
<?
    echo "Hello world";
?>
<?="Hello world"; ?>

<% echo "Hello world"; %>

One should have to stick with standard for making sure further version support guarantee.

Always use Meaningful, Consistent Name Standard

camelCase and underscores are two popular naming standard. In camelCase, the first letter of each word is capitalized, expect for the first word while underscores, adds underscore between words, like

1
mysql_real_escape_string()

.

It’s up to you to choose either naming conventions to do you coding. However, you have to consistent on your coding.

1
2
3
4
5
6
class Foo {
    public function someDummyMethod() {
    }
}
function my_procedural_function_name() {
}

Use the DRY approach

‘Do not Repeat Yourself’ abbreviated for DRY, which is one of the best and useful programming concept and should be used in any programming language like PHP, Java, and C#. Using the DRY approach ensure that no redundant code is there.

A piece of code, violating DRY refers as the WET solution. WET stands for ‘We Enjoy Typing’ or ‘Write Everything Twic’. Check out below given code:

DRY and WET approaches

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

The above given code is based on the WET approach as the relevant parameters are hardcoded. Below given is the DRY approach and code can be updated to.

1
2
3
4
5
6
$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);

Indent Code and Use White Space for Readability

Ensure to have readable and easy to search code by indentations. You should add white space in your code. It is thus, you will surely making changes in the future.

Prevent Deep Nesting

It is fact that many level of nesting would make code difficult to read.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function writeFileFunction() {
// ...
if (is_writable($folder)) {
    if ($fp = fopen($file_path,'w')) {
       if ($stuff = extractSomeStuff()) {
         if (fwrite($fp,$stuff)) {
         // ...
         } else {

         return false;

         }

      } else {

       return false;

     }

    } else {

     return false;

    }

  } else {

   return false;

 }

}

There is no doubt, the code is difficult to read and understand, but, it is sure that it surely improve the readability and reduce the level of nesting as follow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function writeFileFunction() {
// ...

  if (!is_writable($folder)) {

    return false;

  }

  if (!$fp = fopen($file_path,'w')) {

    return false;

  }

  if (!$stuff = extractSomeStuff()) {

    return false;

  }

  if (fwrite($fp,$stuff)) {

   // ...

  } else {

    return false;

  }

}

Avoid putting

1
phpinfo()

in your web root

Phpinfo is a useful function. Users just have to create a simple PHP file with

1
<?php phpinfo(); ?>

and have to paste it to the server as you know everything about your server environment.

But, there are many programmers would place the file contain

1
phpinfo()

in the webroot, which is consider very insecure practice. It results into it could potentially speel doom from the server.

Ensure to place

1
phpinfo()

in the secure sport and it should be delete once you are done.

Try ORM

Using the nifty object relational mapping (ORM) is an excellent ideas to write object-oriented PHP. With object relational mapping, one can easily convert their data between relational databases and object-oriented programming languages. ORM allows working with databases like you are working with classes and objects in PHP. Developers can find loads of ORM libraries for PHP such as Propel and ORm is created into PHP frameworks like CakePHP.

Ensure to Comment

It is advisable to leave comment inside your source code as it is essential when you are involving 5-10 programmers in your project. Comments help to the people, who are maintaining a project from a long time ago.

It is recommended to get educated with some PHP Documentation packages like phpDocumentor to maintain a high quality of comment standard and also take extra time to do it.

PHP Framework

Those developers, who have learned the fundamentals of PHP, can try some PHP frameworks. Different types of PHP frameworks are available that mostly designed on the basis of Model-View Controller (MVC) software architecture.

Moreover, one can learn many interesting and latest things by using a PHP framework. Those who want to create some awesome PHP applications with ease can use framework like Symfony, CakePHP, CodeIgniter, and Zend.

Prevent Deep Nesting

It is advisable to prevent nesting levels as much as possible in your coding. Such things makes thing worsen when you require to debug your code and take the heck out of developers, who will try to review it your code.

In order to avoid unnecessary deep nesting, you should try to use conditions logically as it is poor programming practice and make your code look ugly.

Keep Functions Outside of Loops

Including functions inside of loops delivers excellent performance. The execution time will longer with the larger loop. It is advisable to take some time to put the function outside the loop.

Good example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$count = count($array);

for($i = 0; $i < $count; $i++) {

  //stuff

}

Worst example:
for ($i = 0; $i < count($array); $i++) {

  //stuff

}

“Tier” your Code

Tiering applications means separating the different components of the code into various parts. It allows changing code easily in future. If you want to know how to how to tier your PHP applications for easier maintenance then read this article.

Install MAMP/WAMP

MySQL is one of the most popular types of database that can be used along with PHP. Installing MAMP (Mac) or WAMP (Windows) is possible, if you want to set up a local environment to develop and test PHP applications on your computer.

Developers can find the installation process of MySQL on their computer is tedious one and both of such software packages are drop-in installs of MySQL.

Use Objects (or OOP)

Objects are used by Object-oriented programming that represents parts of the application. Along with breaking the code into separate and logical sections, OOP helps to minimizes code repetition and make it much easier to change for future correction. To know more about write-up on object-oriented programming with PHP, click here.

Never Trust Your Users

One can suppose that they are going to try to input naughty code when application has places for user input. One of the best ways to make your site hacker-free is to initialize your variables to safeguard your site from XSS attacks. PHP.net is one of the best examples of a properly secured form with initialized variables.

1
2
3
4
5
6
7
8
9
&#60;?php
if (correct_user($_POST['user'], $_POST['password']) {
    $login = true;
}
 
if ($login) {
    forward_to_secure_environment();
}
?&#62;

These are some practices that you must try to enjoy the best result. If you want to know more about best practices of the PHP world then ask us through comment. For more information about PHP development and its related things, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA

*