Using PHP to develop robust code three to write reusable functions _php tutorial

Source: Internet
Author: User
In part 3rd of this series of articles (on how to develop effective PHP code in practice), Amol Hatwar discusses how to build the most efficient functional functions, which do not sacrifice too much performance or manageability. The author focuses on how to write reusable functions and describes how to avoid some of the most common problems associated with the task. Welcome back. In the 1th installment of this series, I discussed some basic PHP design rules and described how to write safe, simple, platform-independent, and fast code. In part 2nd, I introduced variables and discussed their use in PHP coding-good and bad practices. In this article, you'll learn how to use functions wisely in PHP. In each of these high-level programming languages, programmers can define functions, and PHP is no exception. The only difference is that you don't have to worry about the return type of the function. In-depth research functions can be used to encapsulate a few lines of code into a single statement. Simplify the code. Most importantly, the product of reconciling applications with smaller applications. The performance level of PHP is astonishing for developers who go to PHP from a compiled language, such as C + +. User-defined functions are expensive to use for CPU and memory resources. This is mainly because PHP is interpreted and loosely typed. Packaging or not, some developers wrap up every function they use simply because they don't like the name of the function, while others don't like to use wrappers at all. Wrapping existing PHP functions without adding or supplementing existing functionality is completely unacceptable. In addition to increasing the size and execution time, such renaming functions can sometimes lead to management nightmares. Inline functions in the code can lead to confusing code, or even a larger management disaster. The only benefit of doing this might be to get a faster code. A more sensible approach is to define a function only if you need to use the code more than once, and you don't have a built-in PHP function available for the task you want to implement. You can choose to rename them or use them only when you need them. The diagram in Figure 1 shows a cursory correlation between manageability and speed versus the number of functions used. (I don't mark the unit here because the numbers depend on the individual and the team's ability; This relationship is an important visual data.) ) Figure 1. Manageability/Speed Vs. function number naming functions as I mentioned in part 2nd of this series (see Resources), it is essential to always use public naming conventions for effective code management. The other two practices to consider are: the name of the selection should be a good indication of function functions. Use the prefix that indicates the package or module. Assume that you have a module named user, which contains users ' management functions, so for a function that checks whether the user is currently online,function names such as Usr_is_online () and Usrisonline () are good choices. Compare the name above with a function name such as Is_online_checker (). The conclusion is that using verbs is better than using nouns, because the function will always do something. How many parameters? It is very likely that you will use a function that has already been constructed. Even if this is not the case, you might want to maximize the use of your code. To do this, you and other developers should continue to develop easy-to-use functions. No one likes to use functions that are obscure and difficult to understand, so write easy-to-use functions. Choosing a name that describes the purpose of the function (and reducing the number of arguments used by the function) is a good way to ensure ease of use. What is the magic number of the number of arguments? In my opinion, more than three parameters make a function difficult to remember. Complex functions that use a large number of parameters can be split into more simple functions. No one likes to use the make-up function. Writing high-quality functions assumes that you want to set the title of the document before placing the HTML document in the browser. Title is... All content between the tags. Assume that you want to set the title and meta tags. Doing all the work without using the SetHeader (title, name, value) function, and using Settitle (title) and Setmeta (name, value), respectively, is a better solution. The program sets the title and meta tags independently of each other. For further consideration, the title can contain only one title tag, but it can contain multiple meta tags. If you need to set multiple meta tags, your code must call Setmeta () multiple times. In this case, a better solution would be to pass a two-dimensional array with a name-value pair to Setmeta () and have the function loop through the array-doing all the operations at the same time. In general, simultaneous functions like this are preferable. Calling functions at once with all the data that a function needs to process is always better than calling the function more than once and providing it incrementally. The main idea when writing a function is to minimize calls to it from other code. Thus, the SetHeader () solution is not a good approach. Obviously, we can make SetHeader () a SetHeader (title, array), but we also have to consider that we have lost the ability to set the title and meta tags independently of each other. In addition, in the real world, the title may contain multiple tags, not just the title and meta tags. If you need to add more tags, you must change SetHeader () and change all other code that depends on it. In the latter case, you only need to write more than one function. The following equations apply to all programming languages: easy-to-remember names + clear parameters + speed and efficiency = high-quality functions that are applicable in all programming languages a hierarchical approach to coordinating function functions is seldom present alone. They work in conjunction with other functions, exchanging and processing data to accomplish tasks. It is important to write a function that works well with other functions in the same group or module, because these function groups or module groups are what you must be able to reuse. Let's continue with the hypothetical page build example. Here, the function of the module is to build a page with HTML. (Now let's skip the details and the code, because the purpose of the example is simply to illustrate: how to make functions and function groups easily fit together as you improve the functionality of reusable features.) Starting with the built-in PHP functions, you can build abstract functions, use them to create more functions to handle the basic requirements, and then use these functions to build application-specific functions in turn. Figure 2 lets you know how it works. Figure 2. Layered functions Now, first build the page in memory and then completePage is distributed to the browser. Building pages in memory has two great benefits: you can cache completed pages with your own scripts. If you fail to build the page successfully, you can discard the half-finished page and point the browser to the error page. Now, your users will not see a report with error messages on the page. Depending on the structure of most pages, you need to divide the page building module into functions that perform the following functions: Draw the top bar to draw the navigation bar display content Add footnotes also need to perform functions such as the following: Cache page Check whether the page has been cached if the page is cached displays it Let's call it the Page Builder (pagebuilder) module. The Page Builder module performs its work by querying the database. Because the database is outside of PHP, the database abstraction module is used to provide a homogeneous interface for various vendor-specific database functions in PHP. Important functions in this module are the functions that connect to the database, the functions that query the database, and the functions that provide the results of the query. Suppose you also want to implement a site-wide search engine. The module will be responsible for searching the site for documents related to a keyword or group of keywords, and displaying the results based on the relevance of the search string or the number of occurrences of that string. If you also want to record a search for auditing, the module will work with the database abstraction module. Keep in mind that you will accept input from the user. You need to display it on the screen and discard what appears to be malicious. This requires another module, which is responsible for validating the data submitted by the user through the form. At this point, you must have a general understanding of the concepts I am talking about. The most core functions must be decomposed into logical modules, and the applications must use the functions provided by these modules to perform their tasks. Using this layered approach, a simple page build rendering application may be shown in 3. Figure 3. Layered page-building applications Note that in this example, there is no hierarchy between the core module and the module that handles the application. That is, the core module can call and declare functions from functions declared in the following abstract module or layer, but the application code may not do so. If a function in your application code is "contaminated" by any low-level function or encapsulates any lower-level function, then the application code should not declare these functions. It can only use lower-level functions. This is proven to be a faster approach. Functional technology Now that you know how to use and write functions, let's look at some common techniques. Using a simple point of reference, a reference is like a pointer in C language. The only difference is that in PHP, you do not need to use the * operator as in C to dereference. You can consider them as aliases for variables, arrays, or objects. The alias affects the actual variable regardless of the action performed. Listing 1 shows an example. Listing 1. VariableReference When a parameter is passed to a function, the function receives a copy of the parameter. Any changes you make to the parameter will be lost as soon as the function returns. This can be a problem if you want to change the parameters directly. Listing 2 shows an example that illustrates the problem. Listing 2. Issues when passing arguments to a function We want to change the $myNum directly; you can do it easily by passing a reference to the $myNum to the half () function. But keep in mind that this is not a good practice. Developers who use your code must keep track of the references they use. This may inadvertently lead to an error spread. It also affects the ease of use of the function. A better practice is to use references directly in function declarations-in our case, using half (& $num) instead of half ($num). Thus, by remembering references, you do not have to remember to pass parameters to the function. PHP handles some things behind the scenes. Newer versions of PHP (from 4.0 onwards) do not favor passing by reference at invocation, and will issue warnings anyway. (Here are some suggestions: if you're using code written for an earlier PHP version, it's a good idea to update the code instead of changing the PHP behavior by changing the php.ini file.) It is often necessary to maintain variable values between function calls by preserving variables between function calls. Global variables can be used, but the variables are very fragile and may be broken by other functions. We want the variable to be a local variable for the function and still retain its value. Using the static keyword is a good solution. I often use this approach when I want to calculate how many user-defined functions are being executed without using the debugger. I just changed all the functions (of course, using an automated script) and added a call to the function that performs the count on the first line of the function body. Listing 3 describes the function. Listing 3. Counts the user-defined function funccount () {static $count = 0; return $count + +;} by calling Funccount () to collect the changes before the script is complete

http://www.bkjia.com/PHPjc/531713.html www.bkjia.com true http://www.bkjia.com/PHPjc/531713.html techarticle In part 3rd of this series of articles (on how to develop effective PHP code in practice), Amol Hatwar discusses how to build the most efficient function functions, using these functions ...

  • 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.