Tutorials to .com

Tutorials to .com » Php » Others » PHP development with robust code (c): the preparation of reusable function

PHP development with robust code (c): the preparation of reusable function

Print View , by: iSee ,Total views: 16 ,Word Count: 3532 ,Date: Sun, 19 Apr 2009 Time: 11:04 PM

In this series of articles (about how to develop practical and effective php code) in Part 3 of, Amol Hatwar was discussed how to build the most effective function of the functional use of these functions will not be sacrificing too much performance or manageability. The author focuses on how to write reusable functions, and introduced how to avoid the tasks associated with some of the most frequently asked questions.
Welcome back. In this series of articles in Part 1, I discussed some basic design rules of PHP, and describes how to prepare safe, simple, fast and platform-independent code. In Part 2, I introduced a variable, and discussed their use of PHP coding - good and bad practice.

In this article, you will learn how to use PHP in a sensible function. In each high-level programming languages, the programmer can define functions, PHP is no exception. The only difference is that you do not have to worry about the return type of function.

In-depth study
Function can be used to:

Package will be a few lines of code into a statement.

Simplify the code.

Most importantly, the application as a smaller application of the product of mutual coordination.
From compiled languages (such as c / C++ + +) to run PHP developer, PHP's performance level is alarming. In the use of CPU and memory resources, user-defined function is very expensive. This is mainly because PHP is interpreted and loose type.

Packaging or not
Some developers just because they do not like the name of function they use every function they are packing up, while some developers simply do not like the use of packaging.

Packing rather than the existing PHP function to add or supplement the existing function, is totally unacceptable. In addition to increasing the size and implementation time, such as rename function can sometimes bring management nightmare.

Inline code function will lead to mysterious code, and even greater disaster management. The only advantage to do so may be a faster code.

More sensible approach is to use only the need for repeated code, and for the task you want to achieve is not available when the built-in PHP function definition of function. You can choose to rename or only when necessary, use only restrictions.

Figure 1 shows a rough diagram manageability and speed of the function and use of the relationship between the number of. (In this I did not identify the unit, because the number depends on the ability of individual and team; this relationship is an important visual information.)

Figure 1. Manageability / Speed Vs. Function of the number of

Named function
As I said in my article in this series, Part 2 (see references) mentioned, it is necessary to have an effective code management, and always use common naming conventions is essential.

The other two need to take into account the practice is:

Should be able to choose the name of a good reminder of the function function.
Show that the package or module to use the prefix.

Assume that you have a user module, which includes user management function, then check the user for a function of current in terms of whether or not online, such as usr_is_online () and usrIsOnline () This function names are a good choice.

To the above name and is_online_checker () function the name of such comparison. Our conclusion is that the use of the verb is better than the use of the term, because it will do function.

The number of parameters?
Is very likely that you will use the function has been constructed. Even if the case is not the case, you may also want to maximize the use of code. To achieve this, you and other developers should continue to develop easy-to-use function. No one likes to use the parameters of those who brought not only obscure and difficult to understand the function, so the preparation of easy-to-use function.

Select a function to use that name (and to reduce the number of function parameters used) is to ensure that a good easy-to-use method. Parameters of the number of magic number what is it? It seems to me that more than three parameters would be difficult for memory function. The use of a large number of parameters of complex functions can be split into a number of almost simple function.

No one likes to improvise a function of use.

The preparation of the Quality Function
The assumption that you would like to put in the HTML document browser settings before the document's title. The title is <head> ...</ head> tags of all of its contents.

The assumption that you want to set title and meta tags. Not to use setHeader (title, name, value) function to carry out all work using setTitle (title) and setMeta (name, value) to complete the work is a better solution. The program set up independently of one another title and meta tags.

Further consideration, the title can only contain a title tag, but it can contain a number of meta tags. If you need to set up a number of meta tags, the code must be called repeatedly setMeta (). In this case, the better solution is to carry the name - the value of the two-dimensional array passed to setMeta (), and let the cycle of the implementation of the array of functions - the implementation of all operations at the same time.

In general, at the same time as a function of such preferable. Function need to be addressed with all the data one-time function call, and always better than multiple calls to functions, and ways to provide incremental data. Function at the time of preparation of the main idea is to minimize the code from other of its call.

Accordingly, setHeader () solution is not a good method. It is obvious that we can setHeader () re-constitute setHeader (title, array), but we must take into account the loss of the title set up independent of each other and the ability of meta tags.

In addition, in the actual environment, the title may contain a number of tags, not just the title and meta tags. If you need to add more markers, you must change the setHeader (), and change it all depends on other code. In the latter case, more than just the preparation of a function.

The following equation applies to all programming languages:

Easy to remember the name of + clear + the speed and efficiency parameter = in all programming languages are applicable to the quality function

Tiered approach with the coordination function
Function rarely exists alone. They work together with other functions, exchange and processing of data in order to complete the task. Prepared with the same group or other function module of the function of a good collaboration is important because these groups function or module that you must be able to reuse.

Let us continue to build a hypothetical example of the page. Here, the module's role is to build a page using HTML. (Now, let us skip the details and code, because the purpose of example only to illustrate: in improving the reusability of the elements at the same time, how to make Group convenient function and function to each other.)

From the built-in PHP function, you can build an abstract function, the use of their basic needs to create more processing function, and then use these functions in order to build application-specific function. Figure 2 can let you know how it works.

Figure 2. Stratification function

Now, the first in memory to build the page, the page will be completed and then distributed to the browser.

Construction of the page in memory, there are two main advantages:

The script can use their own cache of the pages have been completed.

If you did not succeed to build the page, can be abandoned halfway through the page, the browser and point to an error page.
Now, your users will not see an error message page in the report.

According to the majority of the structure of the page, the page building blocks necessary to perform the following functions into the function:

Top column mapping
Map navigation bar
display Properties
Add a footnote
Also need to implement a function of the following features:

Page cache
Check whether the page cache has been
If the page has been displayed its cache
Let us call the page builder (pagebuilder) module.

Page Builder module to query the database through the implementation of its work. Since the database is outside of PHP, so will use the database abstraction module for PHP its responsibilities in a variety of vendor-specific database interfaces provide the same kind of function. The module has an important function: to connect the database function, the function query the database and provide a function of query results.

Assume that you wish to achieve a site-wide search engine. The module will be responsible for the search site with a keyword or group of keywords related documents, and in accordance with the relevance of the search string or number of the string to display the results. If you wish to search records to the audit, the module will use a database abstraction module.

Keep in mind that you will accept input from users. You need to be displayed on the screen, and abandoned those who seemed content with malice. This requires another module, which is responsible for the user to verify the data submitted through the form.

At this point, you talk about the concept I'm sure that has more or less understanding. Must be the most functionality into the core logic module, to perform their tasks, the application must use the functions provided by these modules.

The use of this layered approach, building a simple page showing the application may be as shown in Figure 3.

Figure 3. Stratification to build the application page

Please note that in this example, the core module and processing the application level between the modules. In other words, the core module can abstract from the following modules or layers in a statement a statement of the function call and function, but the application code may not be able to do so. If the application code in a function of low-level function of any "pollution" or package of any low-level function, then the application code should not be a statement of those functions. It can only use low-level function. This was proved to be a faster way.

Functional technology
Since you have already learned how to use and the preparation of function, then let us study some commonly used technology.

The use of reference
Simply put, as quoted in the C language pointer. The only difference is that in PHP, do not need as in C language as the use of * operator to lift the quote. You can them as a variable, array or object alias. No matter what the implementation of the operation, alias will affect the actual variable.

1 demonstrate an example.

1. Variable reference
<? php

$ name = 'Amol';
$ nom = & $ name; / / $ nom is now a reference to $ name
$ nom .= 'Hatwar';

print ( "Are you $ name? n"); / / Jimmy Ray parody?


When the parameters passed to the function, the function to receive a copy of the parameters. As long as the function of a return, you made any changes to the parameters will be lost. If you would like to change the parameters directly, which would be a problem. 2 presentation of a list of the examples of the problem.

List 2. Will be the parameters passed to the function of the problem
<? php

function half ($ num)
$ num = $ num / 2;
return $ num;

$ myNum = 15;
$ result = half ($ myNum);

print ( "The half of $ myNum is: $ resultn");
print ( "$ myNum contains: $ myNumn");


We hope to directly change the $ myNum; of $ myNum by reference to the half () function can easily complete the work. However, please keep in mind that this is not a good practice. The development of the use of your code must be used to track the reference. This may inadvertently lead to the spread of error. It will also affect the function of the ease of use.

Better practice is the direct statement in the function by reference - in our case, the use of half (& $ num) instead of half ($ num). In this way, through reference in mind, you do not need to keep in mind the parameters passed to the function.

PHP behind the scenes to deal with something. Newer PHP version (from version 4.0 from the follow-up), does not support the call by reference, when, and in any case will be issued a warning. (Here are some suggestions: If you are using to prepare for the early versions of PHP code, it is best to update the code, rather than by changing the php.ini file to change the behavior of PHP.)

Retention of variables between function calls
Often the need to preserve the function of the variable values between calls. Can use global variables, but the variable is very fragile and could be damage to other functions. We hope that the variable is the function local variables, and still retain their value.

The use of static keyword is a good solution. When I hope in the debugger can not use the number of cases of user-defined function is executed, I often use this approach. I just changed all the function (of course, is the use of automated scripts), and the first line of body function to add a count of the work of the implementation of the call function. 3 describes the list of the function.

List 3. Counting user-defined function
function funcCount ()
static $ count = 0;
return $ count + +;

Just prior to the completion of the script by calling funcCount () to collect the return value of variables, this method is effective. Surprisingly, $ count is not reset to zero; initialize static variables to implement the line only once.

If you must visit the function of the global variable, then use the variable before you need to use the global keyword.

PHP 4 from the beginning also be able to do so - to use the function, then the definition of it, as long as you do not attempt to declare that it can function twice.

Implementation of dynamic invocation
In many cases, you will find that it is then you do not know which function must be called. When you are in event-driven programming, or when you want to trigger the system when an event outside the specific function call, there will be such a case. Communicate through the network script is an example of this situation.

This method is similar to the use of variable names. As long as the use of an external event to set the variables, and use it as a function (assuming you have the corresponding function declaration). Some confuse it? 4 done to clarify the list.

List 4. Dynamic function call
<? php

function say_hi ()
print ( "Hi!");

function say_greeting ()
print ( "How are you today? n");

function say_bye ()
print ( "Enough functions for the day, I hope to see you again next month.n");
print ( "Till then, have a good timen");

/ / Lets pretend someone just logged in
$ my_func = 'say_hi';
$ my_func ();

/ / Greet the user
$ my_func = 'say_greeting';
$ my_func ();

/ / Call it a day
$ my_func = 'say_bye';
$ my_func ();


When you want to save, they can use this method to prepare a number of switch-case statement to evaluate which function to use. Just set up and use it as a variable function. Although we have deliberately set up a variable, but please keep in mind that the completion of the work can be dynamic, and this shows the features of the technology is so powerful.

Concluding remarks
In this paper, we described how to design and produce high-quality function. We demonstrated how to set each modules and scripts in order to create more applications, we also studied the work can reduce the encoding and generate an excellent source of technology.

The next article, we will note in the PHP classes and objects to the current skills-based to construct and examine some of the implementation of abstract cache and database code.


Developer Shed in the "The Art Of software Development: Understanding Need" article, icarus applications focused on the first part of the development cycle on a sit down to write your first line of code to be something to do.

Please read the Developer Shed on Harish Kamath's Guide "Using PHP with Java"; the Guide contains a detailed illustrative example code, they have been with JDK 1.3.0, Apache 1.3.20 and PHP 4.1.1 on the Linux/i586 tested.

Mike Britton's article, "Scratching the Surface: Getting Started with PHP Fusebox", a complete introduction to the latest version of Fusebox - it is a scalable and effective Web-box-style architecture tools.

PHPGuy Guide provides a "Useful PHP Functions To Build Your PHP Toolkit", provides 10 kinds of unusual function, in the use of PHP coding, you can use these functions to save time.

From the article PHPGuy or: "Making Sense of Those Cold PHP Errors!" Describes several types of PHP errors and how to identify them in the development of the meaning of the period.

PHP Debugger can (free of charge) for a summary of PHP code analysis and debugging.

Paragraph 1 of this series of "strategic foresight" (developerWorks, 2002 years 8 months) to discuss how to master PHP and lay a solid foundation.

Of this series Part 2 of "effective use of variables" (developerWorks, 2002 years 9 months) shows how the resolver configuration file through the structure (using a different variable name) to enable simple configuration script.

DW Linux Area visit for more information.

About the author
Amol Hatwar from Notepad began to contact the computer. As a GNU / Linux supporter of the absolute, he is the last program in the Microsoft platform is guilt. He is now an independent consultant to help as many companies move to GNU / Linux. As a Web application development experts in the field, he left the spare time devoted to the study no one had heard of the technology. His interests include open source software, Web services, peer-to-peer computing, and high-availability cluster.

php other Articles

Can't Find What You're Looking For?

Rating: Not yet rated


No comments posted.