Develop robust code with PHP: write reusable functions

Source: Internet
Author: User
Article title: develop robust code with PHP: write reusable functions. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
In this article, you will learn how to use functions wisely in PHP. In every advanced programming language, programmers can define functions, and PHP is no exception. The only difference is that you don't have to worry about the function return type.
  
   In-depth research
Functions can be used:
  
Encapsulate several lines of code into one statement.
  
Simplified code.
  
The most important thing is to use applications as the product of coordination between smaller applications.
For developers who have switched from a compilation language (such as C/C ++) to PHP, the performance level of PHP is surprising. In terms of CPU and memory resources, user-defined functions are very expensive. This is mainly because PHP is interpreted and loose.
  
   Package or not
Some developers simply wrap every function they use because they do not like the function name, while others do not like the packaging.
  
Packaging existing PHP functions without adding or supplementing existing functions is totally unacceptable. In addition to increasing the size and execution time, such rename functions may sometimes cause management nightmares.
  
Inline functions in the code can cause inexplicable code, or even greater management disasters. The only benefit of doing so may be getting a faster code.
  
The more sensible way is to define a function only when you need to use code multiple times and there is no built-in PHP function available for the task you want to implement. You can choose to rename or use it only when necessary.
  
The chart in figure 1 roughly shows the relationship between manageability and speed and the number of functions used. (I did not specify the unit here, because the number depends on the individual's and team's capabilities; this relationship is important visual data .)
  
   Figure 1. manageability/speed Vs. number of functions
    
Naming functions
As I mentioned in Part 1 of this series of articles (see references), it is always necessary to use public naming conventions for effective code management.
  
The other two practices must be considered:
  
The selected name should be able to properly prompt the function.
Use the prefix indicating the package or module.
  
Assume that you have a module named user that contains user management functions. for functions that check whether a user is online, such as usr_is_online () and usrIsOnline () such a function name is a good choice.
  
Compare the above name with a function name such as is_online_checker. The conclusion is that using a verb is better than using a noun, because a function always performs something.
  
   How many parameters?
It is very likely that you will use the constructed functions. Even if this is not the case, you may want to maximize the scope of use of the code. To achieve this, you and other developers should continue to develop easy-to-use functions. No one prefers to use functions with obscure and difficult-to-understand parameters. Therefore, compile easy-to-use functions.
  
Selecting a name that describes the purpose of a function (and reducing the number of parameters used by the function) is a good way to ensure ease of use. What is the magic number of parameter quantity? In my opinion, more than three parameters will make the function hard to remember. Complex functions that use a large number of parameters can be split into multiple simpler functions.
  
No one prefers to use a function.
  
   Compile high-quality functions
Suppose you want to set the document title before placing the HTML document in the browser. The title is...All content between tags.
  
Assume that you want to set the title and meta tags. Without using the setHeader (title, name, value) function to execute all the work, it is a better solution to use setTitle (title) and setMeta (name, value) to complete the work respectively. This scheme sets the title and meta tags independently of each other.
  
Further, the title can contain only one title tag, but it can contain multiple meta tags. If you need to set multiple meta tags, the code must call setMeta () multiple times (). In this case, a better solution is to pass the two-dimensional array with name-value pairs to setMeta (), and let the function loop to execute the array-and execute all operations at the same time.
  
In general, such simultaneous functions are more desirable. The one-time call of a function with all the data to be processed by a function is always better than calling a function multiple times and provides data for it in incremental mode. The main idea when writing a function is to minimize the number of calls from other code.
  
Therefore, the setHeader () solution is not a good solution. Obviously, we can reconstruct setHeader () into setHeader (title, array), but we must also consider the ability to set the title and meta tags independently of each other.
  
In addition, in the actual environment, the title may contain multiple tags, not just the title and meta tags. To add more tags, you must change setHeader () and all other code dependent on it. In the latter case, you only need to write one more function.
  
The following equation applies to all programming languages:
  
Easy to remember name + clear parameters + speed and efficiency = excellent functions applied in all programming languages
  
   Coordinate functions using a layered approach
Functions rarely exist independently. They work with other functions to exchange and process data to complete the task. It is important to compile functions that can work well with other functions in the same group or module, because these function groups or module groups must be reusable.
  
Let's continue with the hypothetical page building example. Here, this module is responsible for building a page with HTML. (Now let's skip the details and code, because the purpose of the example is to illustrate how to make functions and function groups work together conveniently while improving reusability .)
  
Starting with the built-in PHP functions, you can build abstract functions, use them to create more functions to handle basic requirements, and then use these functions to build application-specific functions in turn. Figure 2 shows how it works.
  
   Figure 2. layered functions
    
Now, first build pages in the memory and then distribute the completed pages to the browser.
  
Building pages in memory has two benefits:
  
You can use your scripts to cache completed pages.
  
If you fail to build the page, you can discard half of the page and point the browser to the error page.
Now, your users will not see any reports with error messages on the page.
  
Based on the structure of most pages, you need to divide the page building module into functions that execute the following functions:
  
Draw top bar
Draw navigation bar
Display Content
Add footer
You also need to execute the following functions:
  
Cache page
Check whether the page has been cached
If the page has been cached, it is displayed.
Let's call it the pagebuilder module.
  
The page builder module performs its work by querying the database. Because the database is out of PHP, the database abstraction module is used to provide similar interfaces for various vendor-specific database functions in PHP. Important functions in this module include database connection functions, database query functions, and functions that provide query results.
  
Assume that you want to implement a site-range search engine. This module searches for documents related to a keyword or a set of keywords on the site, and displays the results based on the relevance of the search string or the maximum number of times the string appears. If you want to record the search for audit, this module will be used with the database abstraction module.
  
Remember that you will accept input from the user. You need to display it on the screen and discard the content that looks malicious. This requires another module that verifies the data submitted by the user through a form.
  
So far, you must have a general understanding of the concept I am talking about. Core functions must be broken down into logical modules. to execute their tasks, applications must use the functions provided by these modules.
  
Using this layered method, simple page building rendering application may be shown in step 3.
  
   Figure 3. layered page building application
  
Note that in this example, there is no hierarchy between the core module and the module that processes the application. That is to say, the core module can call and declare functions declared in the following abstract module or layer, but the application code may not. If the functions in the application code are "contaminated" by any lower-level functions or any lower-level functions are encapsulated, the application code should not declare these functions. It can only use lower-level functions. This proved to be a faster method.
  
   Functional technology
Now that you know how to use and compile functions, let's study some common technologies.
  
   Use reference
Simply put, a reference is like a pointer in C. The only difference is that in PHP, you do not need to use the * operator in the C language to remove the reference. You can think of them as aliases of variables, arrays, or objects. No matter what operation is performed, aliases will affect the actual variables.
  
Listing 1 demonstrates an example.
  
Listing 1. variable reference
     
$ Name = 'amol ';
$ Nom = & $ name; // $ nom is now a reference to $ name
$ Nom. = 'hatwar ';
  
Print ("Are you $ name? \ N "); // Jimmy Ray parody?
  
?>
When a parameter is passed to a function, the function receives a copy of the parameter. As long as the function returns, any changes you make to the parameter will be lost. If you want to directly change the parameter, this is a problem. Listing 2 demonstrates an example of this problem.
  
Listing 2. problems when passing parameters to functions
     
Function half ($ num)
{
$ Num = $ num/2;
Return $ num;
}
  
$ MyNum = 15;
$ Result = half ($ myNum );
  
Print ("The half of $ myNum is: $ result \ n ");
Print ("\ $ myNum contains: $ myNum \ n ");
  
?>
We want to directly change $ myNum. this can be done easily by passing the $ myNum reference to the half () function. But remember, this is not a good practice. The developer who uses your code must track the references used. This may cause errors to spread inadvertently. It also affects the ease of use of functions.
  
A better practice is
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.