Home > Backend Development > PHP Tutorial > Develop Robust Code with PHP 3. Write Reusable Functions_PHP Tutorial

Develop Robust Code with PHP 3. Write Reusable Functions_PHP Tutorial

WBOY
Release: 2016-07-13 17:29:10
Original
728 people have browsed it

In Part 3 of this series on how to develop effective PHP code in real-world situations, Amol Hatwar discusses how to build the most efficient functional functions that can be used without sacrificing too much performance or manageability. The author focuses on writing reusable functions and shows how to avoid some of the most common problems associated with the task. Welcome back. In Part 1 of this series, I discussed some basic PHP design rules and showed you how to write code that is safe, simple, platform-independent, and fast. In Part 2, I introduced variables and discussed their use in PHP coding—good and bad practices. In this article, you will learn how to use functions wisely in PHP. In every high-level 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's return type. Drill Down Functions can be used to: Encapsulate several lines of code into a single statement. Simplify the code. Most importantly, treat the application as a coordinated product of smaller applications. For developers coming to PHP from a compiled language such as C/C++, the performance levels of PHP are astonishing. User-defined functions are very expensive in terms of using CPU and memory resources. This is mainly because PHP is interpreted and loosely typed. Wrapper or not Some developers wrap every function they use simply because they don't like the name of the function, while other developers don't like using wrappers at all. Wrapping existing PHP functions without adding or supplementing existing functionality is completely unacceptable. In addition to increasing size and execution time, such renamed functions can sometimes create an administrative nightmare. Inline functions in your code can lead to baffling code and even greater management disasters. The only benefit of doing this may be faster code. A smarter approach is to only define functions when you need to use the code multiple times and there are no built-in PHP functions available for the task you want to achieve. You can choose to rename it or use it with restrictions only when needed. The graph in Figure 1 roughly shows how manageability and speed relate to the number of functions used. (I’m not specifying units here because the numbers depend on individual and team capabilities; this relationship is important to visualize.) Figure 1. Manageability/Speed ​​vs. Number of functions Naming functions As I’ve done in this series of articles As mentioned in Part 2 (see Resources), for effective code management, it is essential to always use a common naming convention. Two other practices to consider are: Choose a name that gives a good hint of what the function does. Use a prefix that indicates the package or module. Assuming you have a module called user that contains user management functions, function names such as usr_is_online() and usrIsOnline() are good choices for functions that check whether the user is currently online. Compare the name above to a function name like is_online_checker(). The conclusion is that using verbs is better than using nouns because functions always do something. How many parameters? Most likely you will be using an already constructed function. Even if this is not the case, you may want to maximize the scope of your code. To do this, you and other developers should continue to develop functions that are easy to use. No one likes to use functions with parameters that are obscure and difficult to understand, so write functions that are easy to use. Choosing a name that explains the function's purpose (and reducing the number of arguments the function takes) is a good way to ensure ease of use. What is the magic number for the number of parameters? In my opinion, more than three parameters make the function difficult to remember. Complex functions with a large number of parameters can almost always be split into simpler functions. No one likes to use makeshift functions. Writing Good Functions Suppose you want to set the title of your HTML document before you put it in the browser. The title is everything between the

... tags. Suppose you want to set the title and meta tags. Instead of using the setHeader(title, name, value) function to do all the work, a better solution would be to use setTitle(title) and setMeta(name, value) to do each work separately. This scheme sets the title and meta tags independently of each other. Thinking further, a title can contain just one title tag, but it can contain multiple meta tags. If multiple meta tags need to be set, the code must call setMeta() multiple times. In this case, a better solution is to pass a two-dimensional array of name-value pairs to setMeta() and have the function loop over the array — all at the same time. In general, simultaneous functions like this are preferable. Calling a function once with all the data it needs to process is always better than calling the function multiple times and feeding it data incrementally. The main idea when writing functions is to minimize calls to them from other code. According to this, the setHeader() solution is really not a good idea. Obviously, we can refactor setHeader() into setHeader(title, array), but we must also consider that we lose the ability to set the title and meta tags independently of each other.Also, in a real environment, the title may contain multiple tags, not just title and meta tags. If you need to add more markup, you must change setHeader(), and all other code that depends on it. In the latter case, just write one more function. The following equation applies to all programming languages: Memorable names + clear arguments + speed and efficiency = good functions in all programming languages ​​Coordinate functions in a layered approach Functions rarely exist alone. They work with other functions to exchange and process data to complete tasks. It's important to write functions that work well with other functions in the same group or module, because these groups of functions or modules are the ones you must be able to reuse. Let's continue with the hypothetical page building example. Here, the responsibility of this module is to build a page using HTML. (Let's skip the details and code for now, since the purpose of the example is just to illustrate how functions and groups of functions can easily work together while increasing the reusability factor.) Starting with the built-in PHP functions, you can Build abstract functions, use them to create more functions that handle basic needs, and then use these functions in turn to build application-specific functions. Figure 2 gives you an idea of ​​how this works. Figure 2. Layered functions Now, the page is built in memory and then the completed page is dispatched to the browser. Building pages in memory has two major benefits: You can cache completed pages with your own scripts. If the page doesn't build successfully, you can scrap the half-finished page and point the browser to an error page. Now, your users will no longer see reports with error messages on the page. Depending on the structure of most pages, the page building blocks need to be divided into functions that perform the following functions: Draw the top bar Draw the navigation bar Display content Add footnotes You also need functions that perform the following functions: Cache the page Check whether the page has been cached If the page Already cached it displays let's call it the pagebuilder module. The page builder module performs its work by querying the database. Since the database is external to PHP, you will use the Database Abstraction Module, whose responsibility is to provide a homogeneous interface to the various vendor-specific database functions in PHP. The important functions in this module are: functions to connect to the database, functions to query the database, and functions to provide query results. Suppose you also want to implement a site-wide search engine. This module will be responsible for searching the site for documents related to a certain keyword or set of keywords and displaying the results based on the relevance of the search string or the most occurrences of that string. This module is used together with the Database Abstraction module if you also wish to log searches for auditing purposes. Remember that you will be accepting input from the user. You need to get it on the screen and discard content that looks malicious. This requires another module, which is responsible for validating the data submitted by the user through the form. By now, you must have a general idea of ​​the concepts I'm talking about. The most core functionality must be broken down into logical modules, and to perform their tasks, applications must use the functions provided by these modules. Using this layered approach, a simple page-building rendering application might look like Figure 3. Figure 3. Layered page building application Note that in this example there is no hierarchy between the core module and the modules that handle the application. That is, core modules can call and declare functions from functions declared in abstract modules or layers below, but application code may not be able to do so. Application code should not declare functions in application code if they are "polluted" by or encapsulate any low-level functions. It can only use low-level functions. This proved to be a faster method. Functional Techniques Now that you understand how functions should be used and written, let's examine some common techniques. Using References Simply put, references are like pointers in the C language. The only difference is that in PHP, you don't need to use the * operator to dereference as in C. You can think of them as aliases for variables, arrays, or objects. No matter what you do, the alias will affect the actual variable. Listing 1 demonstrates an example. Listing 1. Variable reference When you pass an argument to a function, the function receives a copy of the argument. Any changes you make to the parameters will be lost as soon as the function returns. This can be a problem if you wish to change parameters directly. Listing 2 shows an example that illustrates this problem. Listing 2. Problems when passing arguments to functions We want to change $myNum directly; this is easily done by passing a reference to $myNum to the half() function. But keep in mind that this is not a good practice.Developers using your code must keep track of the references used. This can inadvertently cause errors to spread. It also affects the ease of use of the function. Better practice is to use the reference directly in the function declaration — in our case, use half(&$num) instead of half($num). This way, by remembering the reference, you don't have to remember to pass arguments to the function. PHP handles some things behind the scenes. Newer PHP versions (and subsequent versions from 4.0 onwards) deprecate passing by reference when calling, and will issue a warning anyway. (Here are some suggestions: If you are using code written for an earlier version of PHP, it is better to update the code rather than changing the behavior of PHP by changing the php.ini file.) Preserving variables between function calls often requires maintaining functions Variable values ​​between calls. Global variables can be used, but variables are very fragile and can be corrupted by other functions. We want the variable to be local to the function and still retain its value. Using static keyword is a good solution. I often use this method when I want to count how many user-defined functions were executed when the debugger is not available. I just changed all the functions (using automated scripts of course) and added a call to the function that does the counting work on the first line of the function body. Listing 3 describes this function. Listing 3. Counting user-defined function function funcCount() { static $count = 0; return $count++; } Collect variables by calling funcCount() just before the script completes

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/531713.htmlTechArticleIn Part 3 of this series on how to develop effective PHP code in real-world situations, Amol Hatwar discusses how to build the most efficient functional functions using these...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template