Use PHP to develop robust Code 3 and write reusable functions

Source: Internet
Author: User
In part 2 of this series of articles (about how to develop effective PHP code under actual conditions), AmolHatwar discusses how to build the most effective functional functions, using these functions does not sacrifice much performance or manageability. The author focuses on how to write reusable functions and introduces how to avoid conflicts with SyntaxHighlighter. all ();

In part 2 of this series of articles (about how to develop effective PHP code under actual conditions), Amol Hatwar discusses how to build the most effective functional functions, using these functions does not sacrifice much performance or manageability. The author focuses on how to write reusable functions and introduces how to avoid some of the most common problems related to the task. Welcome back. In part 1 of this series, I discussed some basic PHP design rules and introduced how to write secure, simple, platform-independent, and fast code. In Part 2, I introduced variables and discussed their usage in PHP encoding-good and bad practices. 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 to 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. Packaging or not some developers simply wrap every function they use because they do not like the function name, while others do not like packaging at all. 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. the number of function naming functions, as I mentioned in section 2nd of this series (see references), need effective code management, it is essential to always use public naming conventions. The other two practices need to 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. Writing high-quality functions assumes that 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 applicable in all programming languages use a layered approach to coordinate function 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. hierarchical functions now build pages in the memory and then distribute the completed pages to the browser. There are two benefits for building pages in the memory: you can use your own 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: to draw the top bar, draw the display content in the navigation bar, add a footer, and perform the following functions: the cache page checks whether the page has been cached. if the page has been cached, it is displayed as 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. layer-based page building applications note that in this example, there is no layer 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. Since you have learned how to use and compile functions, let's look at some common technologies. 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 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 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 to directly use references in the function declaration-in our example, use half (& $ num) instead of half ($ num ). In this way, you do not need to remember to pass parameters to functions by remembering references. PHP handles some things behind the scenes. Newer PHP versions (later versions starting from 4.0) do not support passing by reference during calls, and warnings will be issued in any case. (Here are some suggestions: If you are using code written for earlier PHP versions, it is best to update the code instead of modifying the php. ini file .) To retain the variables between function calls, you often need to maintain the variable values between function calls. Global variables can be used, but the variables are very fragile and may be damaged by other functions. We want the variable to be a local variable for the function and keep its value. Using the static keyword is a good solution. This method is often used when I want to calculate how many user-defined functions are executed without using the debugger. I just changed all the functions (of course using automated scripts) and added a call to the function that executes the counting work in the first line of the function body. Listing 3 describes the function. Listing 3. counting user-defined function funcCount () {static $ count = 0; return $ count ++;} calls funcCount () to collect changes just before the script is complete.

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.