الخميس، 5 فبراير 2015

PHP Coding Styles & Standards

No matter how much proficient you are in PHP, no matter how much do you know about the in and out of the language syntax or functions, it is very simple and easy to write obfuscated and sloppy code. But such kind of code is very difficult to debug and maintain. If you are proficient in PHP and writing hard-to-read code, then it means you are having a lack of professionalism. So here you’ll find out some PHP coding styles & standards to improve your coding style.

Indentation

Although indentation or any code styling is not mandatory in PHP, but is a very nice visual organization tool that you should always consistently apply to your code. Check the following example without indentation.
1
2
3
4
5
6
7
if($day == 'Sunday' || $month == 'April') {return 30;
}
else if($day == 'Monday') {
if($month == 'January') {
return 29;
}
}
Above code is very hard to read and understand. Now compare the above code the below one:
if($day   == ‘Sunday’ ||
   $month == ‘April’) {
   return 30;
}
else if($day == ‘Monday’) {
    if($month == ‘January’) {
        return 29;
    }
}
You can see the difference between the two that which code snippet is clear. So using indentation is a good strategy to clear up your code.

Using Whitespace

Using whitespace is also a good strategy to reinforce and provide logical structure in code. You may use whitespaces to group assignments and show associations. Check the code below without whitespaces:
1
2
3
4
5
$local_time = localtime();
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$month = $_REQUEST['month'];
$day = $_REQUEST['day'];
Above code seems messy because, I couldn’t find logical group related assignments clearly. So now check the below code with whitespace.
$local_time    = localtime();
$name            = $_REQUEST[‘name’];
$email            = $_REQUEST[‘email’];
$month          = $_REQUEST[‘month’];
$day               = $_REQUEST[‘day’];

Using Braces in Control Structures

Most of the PHP code is adopted by the C programming language. As we could see in C, a single line conditional statement doesn’t require braces in PHP. But you should use code like below with control structures in PHP.
if(isset($email)) {
    echo ‘Email is correct';
}
else {
    echo ‘Email not correct';
}

Using continue & break to Control Flow in Loops

When you are writing a code in a loop, you can utilize PHP break to jump out blocks when you feel no need to be there. Check the code below:
while(($getLine = fgets($fileOpen)) !== false) {
    if(strcmp($getLine, ‘_END’) == 0) {
      break;
    }
    if(strncmp($getLine, ‘//’, 3) == 0) {
     continue;
    }
}

Global and Constants Variables

You should always use global and constant variables in uppercase letters. So you can easily identify them as constant or global variables.

Long-Lived Variables

Write long-lived variables descriptive and concise. Because it aid readability and make the large section of code easy to read. Now question is what are long-lived variables? These variables are used through any significant length of code and/or whose representation can use clarification. For example, $cacheFiles.

Temporary Variables

Temporary variables should be concise and short in length. Because these variables usually live only within a small section of code. For example, replace $number_of_parent_indices to $pcount.

Function Names

You should handle function names as variable names. For example, they should be separated by underscores and all in lowercase. But when it comes to braces, try to use classic style to separate function declarations from other conditional types.
function say_hello($text)
{
     echo “Hello $text”;
}

Multiword Names

If you want to use variable to have multiple words, then you can apply two methods. Either you should use mixed case like $cacheFiles or you can use separated by commas like $cache_files.

Class Names

When writing class names, you should follow the following guidelines:
1. Multiword class names should be concatenated, and the first letter of each world should be capitalized.
2. Use underscores to simulated nested namespaces.
3. Keep first letter of the word capitalized. Because this visually distinguishes a class name from a member name.
For example, Text_PrettyPrint{} or XML_RSS {}.

Method Names

Method names should be in mixed case like below:
class Test_Class
{
        function casheFiles() {}
}

Naming Consistency

Variables that are used for the same purpose should have similar names. For example, if you are getting maximum, minimum or sum of some specific elements or variables. Then use variables like below:
$sum_elements;
$min_elements;
$max_elements;

Avoid to Use Open Tags

Don’t use open tags, because there may be the time you are also using complete tags. For example replace
<?
echo “Hello”;
?>
To
<?php
echo “Hello”;
?>

Don’t Construct HTML Using Echo

PHP also has one great beauty to embed HTML in PHP or vice versa. For example:
1
2
3
4
5
6
7
8
<?php
echo "<table>";
echo "<tr><td>Name</td><td>Position</td></tr>";
foreach ($employees as $employee) {
echo "<tr><td>$emplaoyee[name]</td><td>$employee[position]</td></tr>";
}
echo "</table>";
?>
But writing code like above is not a good strategy. Instead write like:
Select Code
1
2
3
4
5
6
<table>
<tr><td>Name</td><td>Position</td><tr>
<?php foreach ($employees as $employee) { ?>
<tr><td><?php echo $emplaoyee[name]; ?></td><td><?php echo $employee[position]?></td></tr>
<?php } ?>
</table>

ليست هناك تعليقات:

إرسال تعليق