News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

Develop rock-solid code in PHP

Started by ben2ong2, October 06, 2006, 10:48:58 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

By Amol Hatwar

Intended Audience
This tutorial is intended for both amateur and professional PHP programmers who want to design and write quality functions. To complete this tutorial, you must have a basic level of working knowledge with PHP, and know how to define functions.
Introduction
Welcome back. In Part 1 of this series, we discussed some basic PHP design rules, and covered how to write secure, simple, platform-independent, speedy code. In Part 2, we explored the world of variables and discussed their usage - both good and bad - in PHP coding. In this article we'll deal with how to use functions in PHP wisely.

Every high-level programming language allows the programmer to define functions. PHP is no different.
A closer look at writing functions
Functions are primarily used to:
·   Encapsulate several lines of code into a single statement
·   Simplify and reuse code
·   Treat the application as a collection of smaller applications working harmoniously.
For developers who come to PHP from compiled languages such as C/C++, PHP's level of performance comes as a shock. User-defined functions are more expensive in terms of CPU and memory resources. But if you design and code your functions properly, you’ll be in safe waters.
The name game
The advantage of using a common naming convention throughout can’t be overstressed. Use the following guidelines when naming functions:
·   Choose names that provide a good hint about what the function does
·   Use prefixes that indicate the package or module the function belongs to
·   Use verbs as function names, rather than nouns.
Suppose you have a module named “user”, which contains user-management functions. Then function names such as usr_is_online() and usrIsOnline() are good candidates for a function that handles checking if the user is currently online. Contrast this with a function name such as is_online_checker(). Using verbs as function names is more logical than using nouns, because functions always do something.
To wrap or not to wrap?
There are developers who wrap every function they use just because they don't like the name. Then there are others who don't like wrapping functions at all. While wrapping may add little overhead in compiled languages, the same is not true in PHP.

Wrapping existing PHP functions without adding or complementing existing functionality should be avoided. Besides increasing the size and the execution time, such renamed functions can turn code management into a nightmare.
How many arguments?
In order to maximize the reach of your code, both for yourself and for other developers, you must write functions that are easy to use. No one likes to use functions with cryptic and hard-to-follow arguments.

Choosing a name that explains the purpose of the function as well as and keeping to a minimum the number of arguments the function takes, are good ways to ensure ease-of-use (EOU). Many argue over the magic number for function arguments. In my opinion more than three or four arguments make a function less memorable. Complex functions that need more arguments should rather be broken down into several simpler functions.

Another trick is to glue smaller arguments to a single large one. One mentionable example here is the PEAR DB's connect() function. The function takes a string called the Data Source Name (DSN) plus a Boolean value that indicates whether or not to use persistent connections.
You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login

ben2ong2


This DSN is actually many parameters cemented into a string. If you are connecting to a MySQL database named 'foobar' with the username: 'john' and password: 'doe' on a host called: 'spydor'; the DSN would be 'You are not allowed to view links. Register or Login;. All done in one argument! Contrast this with the plethora of functions one has to call using PHP’s native MySQL support just to connect to a database.

However, to make sense of the DSN from any other string, DB::connect() has to be internally separated into individual arguments like the username, password, hostname, database type and the database name always an additional step. Since things like making connections to a database are generally done only once in a script, gluing strings together to make a single argument and separating them doesn't have a serious impact on performance. Steer clear of functions that parse arguments internally if you have to use them in a script regularly, for example in loops.
Write quality functions
Say you want to set the header-block of an HTML document before pushing it off to the browser. (The header-block is all the stuff between the <head>...</head> tags.) Assume that you want to set both a title and a meta tag. Instead of an odd setHeader({title/meta}, name, value="") function that does it all, using setTitle(title) and setMeta(name, value) separately is a better solution. This sets the title and the meta tags independently of each other.

A header can have only one title tag, but it can have multiple meta tags. When that happens the code will have to call setMeta() multiple times. In such cases, a better solution is to pass setMeta() a two-dimensional array with name-value pairs, and have the work done in one fell swoop.

In general, one-shot functions such as this one are preferable. It's always better to call a function once with all the data it needs to process rather than to invoke it multiple times and feed it arguments incrementally at each call. The idea here is to write a function to minimize calls to it from other code.

In this light, our setHeader() solution was really a kludge. We can obviously refractor setHeader() to setHeader(title, array="") - where the array contains all the name-value pairs for the meta tag. But we must also consider the lost ability to set the title and meta tags independently of each other.

Also, in real-world environments a header can contain more tags than just title and meta. If suddenly, more tags need to be added after an application is ready, one will have to change setHeader() and alter all other code that depends on it. On the other hand, if the setTitle() and setMeta() approach was, used the change would only require writing one more function and then using it.
Optimizing functions
Many developers make the mistake of trying to optimize functions prematurely. The moment they find that they have a useful function at hand, they’ll get down to optimizing it. Remember that optimization is a relatively late step, and is best done when your Web application is ready. With the increasing time-to-deploy expectations that clients have these days, it makes perfect sense to complete the Web application, wait and see which functions get hit most, and then optimize them.

The following equation is a good recipe for writing quality functions:
Memorable name + Unambiguous arguments + Speed and efficiency = Quality function
The layered approach
Functions seldom exist in a vacuum. They work with other functions, exchanging and processing data to get tasks done. Writing functions that work well with other functions in the same group or module is important because it's precisely these groups of functions or modules that one would like to be able to reuse.

You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login