| Writing Good Php Code |
|
| Written by ircmaxell | |||||
| Monday, 02 April 2007 | |||||
Page 2 of 3
Structure Your Code Block Level Structures One of the easiest ways to tell a new programmer from an experienced one is the way the code looks. Most new programmers simply write the code as a big group of lines, which incidentally works. That is, it works until you have a missing } or ; in your code. Then the pitfalls of line by line programming become painfully apparent. You can make things much easier on yourself if you simply structure your code. Here is an example of unstructured vs. structured code. if($result==true) { for($x=1;x<=3;$x++) { echo $resuly.$x; }} Or. if($result == true) { for( $x = 1; $x <= 3; $x++ ) { echo $result . $x; } } Again, as with most examples in this book, this example is trivial. However, when you find yourself with multiple different block level operations (if, for, while, etc…), structuring your code can make a huge difference in debugging and readability. While the character(s) that you use to structure the code are not important (tab, three spaces, six spaces, etc), the important thing is BE CONSISTANT. If you use 3 spaces as your delimiter, than use three spaces throughout your program. Changing back and forth between them is asking for trouble later on. I personally do not like to use the tab delimiter, because it is incompatible with some input methods (browser text box editors for example). Something to note; when using if statements (and all block level structures for that matter), if the statement following the structure is one line in length, then no curly braces ({}) are needed. If the statement is more than one line, the curly braces are always needed. Here’s an example: If($something == true) onlything(); And. If($something == true) { Onething(); Secondthing(); }
Functions I cannot stress enough how important and how powerful functions can be. If you know and understand functions, and use them, you can skip to the next section. Otherwise, please read on. Functions allow you to isolate and move code around. They allow you to stop repeating similar code several times in a program. For example, if you need to get the user name associated with a user id, you could do the following (each time): $sql = “SELECT name FROM user_data WHERE id = “ . $user_id; $name = ExecuteQuery($sql); if (!isstring($name)) echo ‘ there’s an error!’; Or simply have the following somewhere in the code function user_name_from_id($user_id) { $sql = “SELECT name FROM user_data WHERE id = “ . $user_id; $result = ExecuteQuery($sql); if (!$result) echo ‘there’s an error!’; else return $result; } Now, any time you need to get the name from a user id, you just need to write $name = user_name_from_id($user_id). The real power in this is not really in the reduction of code (This is a big benefit, but not as much as the other major benefit), but in the abstraction of the code. What I mean by abstraction is this; If you want to add functionality later on (lets say error handling), if you had 100 instances of the same code, you’d spend more time finding the code to edit than actually editing it. So by putting the code in a function, you allow yourself the ability to make changes. Let say that we decided that instead of printing “There’s an error” if the user_id doesn’t match any records, we decided to set the user name to “Hacker”. So instead of hunting every instance of the code, and replacing “echo ‘there’s an error!’” in each one, you can simply edit the function once. Functions also add to the readability of the code. By breaking down lines of code into meaningful blocks (with meaningful names), you can make debugging and expanding much easier. Another key benefit of functions is their ability to become portable. Basically, if you do the same thing in several programs, you can create a file of common functions that you program with so there is less that you need to write. Normally, databases are great places for custom functions to carry over from one program to another, but ideally database functions belong in another area: Classes. Classes There are two ways of thinking about classes. The first is that they are collections of methods (functions) and variables. The better way of thinking about them is as a flexible framework of methods and variables. This is the best area for dealing with database functions. Classes allow you to create a set of functions and variables, and then assign them to an object (variable). The power in classes is that you can create different classes that have the same framework for compatibility. Think about databases; If you only ever use MySQL, then you probably can do without a database class (it does make life easier, but not that much). But if you use MySQL sometimes, and MS SQL others, and ProgreSQL other times, then it becomes really easy. You can write three classes (database_mysql, database_mssql and database_progresql) with the same internal structure. Now, you can write your program to work with the common framework, and simply use the class that fits the database type you need. For Example: Class database_mysql { Var $connection; Var $type = “mysql”;
// When writing a class in PHP, if a function has the same name as the // class, it is automatically called whenever the class is declared. Function database_mysql($user, $pass, $host, $db_name) { //connect to database and store connection into $this_connection }
Function ExecuteQuery($sql) { // Execute $sql and return result } } Class database_progresql { Var $connection; Var $type = “progresql”; Function database_mysql($user, $pass, $host, $db_name) { //connect to database and store connection into $this_connection } Function ExecuteQuery($sql) { // Execute $sql and return result } } Now, in your code, you can load either one, and execute the same functions. $database_mysql = new database_mysql(‘user’,’password’,’localhost’,’db_name’); $database_progresql = new database_progresql(‘user’,’password’,’localhost’,’db_name’); $sql = “SELECT * FROM mysql_table”; $result = $database_mysql->ExecuteQuery($sql); $result = $database_progresql->ExecuteQuery($sql); $database_mysql2 = new database_mysql(‘new user’,’password’,’localhost’,’db2’); Now, if you use a configuration file in your program, you could add a setting for database type. Then, you can choose which database class to load based on the setting (You can do this because the frameworks are the same!). See the power? Classes don’t just need to be about data access either. They can be used for data storage and manipulation as well. Imagine that you are creating a section for user administration. You could create a class that stores the information of one user, as well as the necessary functions for administration. Then, each time you need to edit a user, just declare an instance of the class, and there you go. The entire point of structuring your programs is for readability, portability and ease of editing. A good rule of thumb for creating functions is if you use similar code more than twice in your program, you should create a function to do the task (such as verifying access). A good rule of thumb for creating classes is if you have code that needs to be interchanged on the fly, make a class (such as templates). Used properly, classes and functions can make a complex program very easy. Used improperly, classes and functions will make a simple program very difficult. The point I am trying to make with these last two sentences is this; you NEED to learn and use classes and functions. Just don’t over do it… |
|||||
| Last Updated ( Thursday, 05 July 2007 ) | |||||
| < Prev |
|---|











