Chapter 3PHP Best Practices IN THIS CHAPTER ◆ Best practices for naming variables and functions or methods ◆ Best practices for functions or methods ◆ Best practices for database ◆ Best
Trang 1Chapter 3
PHP Best Practices
IN THIS CHAPTER
◆ Best practices for naming variables and functions or methods
◆ Best practices for functions or methods
◆ Best practices for database
◆ Best practices for user interface
◆ Best practices for documentation
◆ Best practices for configuration management
T HE APPLICATION CODE PRESENTEDin this book uses a set of programming practices that qualify as best practices for any PHP application development This chapter discusses these practices Familiarizing yourself with them will ease the learning curve for the applications discussed in the rest of the book
Best Practices for Naming Variables and Functions
Top software engineers know that good variable, function (or method), and class names are necessary for the maintainability of the code A good name is one that conveys meaning related to the named function, object, class, variable, etc
Application code becomes very difficult to understand if the developers don’t use good, meaningful names Take a look at the following code sample:
<?php error_reporting(E_ALL);
$name = (! empty($_REQUEST[‘field1’])) ? $_REQUEST[‘field1’] : “Friend”;
outputDisplayMsg(“Hello $name”);
exit;
41
Trang 2function outputDisplayMsg($outTextMsgData = null) {
echo $outTextMsgData;
}
?>
Now look at the same code segment with meaningful names for variables and functions:
<?php error_reporting(E_ALL);
$name = (! empty($_REQUEST[‘field1’])) ? $_REQUEST[‘field1’] : “Friend”; showMessage(“Hello $name”);
exit;
function showMessage($outTextMessageData = null) {
echo $outTextMessageData;
}
?>
The second version is clearly easier to understand because showMessage is a bet-ter name for the outputDisplayMsg function
Now let’s look at how you can use easy-to-understand names for variables, functions (or methods), and classes
When creating a new variable or function name (or method), ask yourself the following questions:
◆ What is the purpose of this variable? In other words, what does this vari-able hold?
◆ Can you use a descriptive name that represents the data the variable holds?
◆ If the descriptive name appears to be too long, can you use meaningful abbreviations? For example, $textMessageis as good as $txtMsg Names exceeding 15 characters probably need to be reconsidered for abbreviation
Trang 3After you determine a name, follow these rules:
◆ Use title casing for each word in multiword names However, the very
first word should be lowercase For example, $msgBodyis a better name then $msgbody, $messageBODY, or $message_body Single word names should be kept in lowercase For example, $path and $data are single word variables
◆ Use all capital letters to name variables that are “constant like” — in other words, variables that do not change within the application For
example, if you read a variable from a configuration file, the name of the variable can be in all uppercase To separate uppercase words, use under-score character (for example, use $TEMPLATE_DIRinstead of $TEMPLATE-DIR) However, when creating constants it is best to use define() function For example, define(PI, 3.14)is preferred over $PI = 3.14 The defined constant PI cannot be changed once defined whereas $PI can
be changed
◆ Use verbs such as get, set, add, delete, modify, update, and so forth in naming your function or method For example, getSomething(), setSomething(), and modifySomething()are better function names than accessSomething(), storeSomething(), and editSomething(), respectively
Best Practices for Function/Method
In this section I discuss a set of practices that will improve your function or method code
Returning arrays with care
When your function (or method) returns an array, you need to ensure that the return value is a defined array because the code from which the function is called
is expecting an array For example, review the following bad code segment
// BAD function getData() {
$stmt = “SELECT ID, myField1, myField2 from myTable”;
$result = $this->dbi->query($stmt);
Trang 4if ($result != NULL) {
while($row = $result->fetchRow()) {
$retArray[$row->ID] = $row;
} } return $retArray;
}
In this example, the function called getData() returns an array called
$retArraywhen the SQL statement executed returns one or more rows The func-tion works fine if the SQL select statement always returns at least one row However, it returns nothing when the SQL statement returns no rows In such a case, the following code segment, which calls the function, produces a PHP warn-ing message:
error_reporting(E_ALL);
$rowObjectArray = $this->getData();
while(list($id, $rowObject) = each($rowObjectArray)) {
// do something here }
$rowObjectArray causes each() to generate a warning when the myFunction() method fails to return a real array Here’s a better version of the getData()method:
// GOOD function getData() {
$retArray = array();
$stmt = “SELECT ID, myField1, myField2 from myTable”;
$result = $this->dbi->query($stmt);
if ($result != null)
Trang 5{ while($row = $result->fetchRow()) {
$retArray[$row->ID] = $row;
} } return $retArray;
} The second version of getData() function initializes $retArray as an array, which ensures that functions such as each()do not complain about it
You can avert PHP warning messages by initializing arrays using array()
Simplifying the function or method argument list order issue
When a function or method has many arguments, as shown in the following code, bugs are more likely to appear because of data mismatches in function calls
// Not So Good function myFunction($name = null,
$email = null,
$age = null,
$addr1 = null,
$addr2 = null,
$city = null,
$state = null,
$zip = null )
{ echo “Name = $name\n”;
echo “Email = $email\n”;
echo “Age = $age\n”;
echo “Address 1 = $addr1\n”;