PHP code Reconstruction

Source: Internet
Author: User
As PHP changes from a simple scripting language to a mature programming language, the complexity of a typical PHP application code library increases. To control the support and maintenance of these applications, we can use various testing tools to automate the process. One of them is unit testing, which allows you to directly test the correctness of the written code.

As PHP changes from a simple scripting language to a mature programming language, the complexity of a typical PHP application code library increases. To control the support and maintenance of these applications, we can use various testing tools to automate the process. One of them is unit testing, which allows you to directly test the correctness of the written code.

As PHP changes from a simple scripting language to a mature programming language, the complexity of a typical PHP application code library increases. To control the support and maintenance of these applications, we can use various testing tools to automate the process. One of them is unit testing, which allows you to directly test the correctness of the written code. However, the legacy code library is generally not suitable for such tests. This article describes how to refactor PHP code that contains frequently asked questions, so as to simplify the testing process using popular unit test tools and reduce the dependence on the improved code library.

Introduction

Looking back on the development history of PHP over the past 15 years, we found that it has changed from a simple dynamic scripting language used to replace the popular CGI script to a mature modern programming language. As the code library grows, manual testing has become an impossible task. Large or small, changes in code will affect the entire application. These effects may be as small as they only affect the loading of a page or the storage of forms. They may also cause problems that are difficult to detect or generate errors that only occur under specific conditions. Even, it may cause previously fixed problems to reappear in the application. Therefore, many testing tools have been developed to solve these problems.

One of the popular methods is the so-called function or acceptance test, which tests the application through typical user interaction of the application. This is a method that is suitable for testing various processes in an application. However, the testing process may be very slow and it is generally impossible to test whether the underlying classes and methods work properly as required. In this case, we need to use another test method, namely unit test. The purpose of unit testing is to test the underlying code functions of an application and ensure that they produce correct results after execution. In general, these "increasing" Web applications will gradually become more and more legacy code that is difficult to test over time, making it difficult for the development team to ensure the coverage of application testing. This is often called "untestable code ". Now let's take a look at how to identify untestable code in an application and how to fix it.

Identify codes that cannot be tested

The problem about the non-testability of the code library is usually not obvious during code writing. When writing PHP application code, people tend to write code according to the Web request process, which is usually a more streamlined method in application design. Eager to complete the project or quickly fix the application may prompt developers to "take shortcuts" to quickly complete coding. In the past, improper or confusing code may aggravate the non-testable problem in the application, because developers often fix the problem with minimal risk, even if it may cause subsequent support problems. These problem domains cannot be found through general unit tests.

Functions that depend on the Global Status

Global variables are convenient in PHP applications. They allow you to initialize some variables or objects in the application and then use them elsewhere in the application. However, this flexibility comes at a cost, and excessive use of global variables is a common problem that cannot be tested. We can see this in Listing 1.

Listing 1. Global-dependent functions

 
 

These global variables bring about two different problems. The first problem is that you need to consider all these global variables in the test to ensure that they are set with valid values acceptable to the function. The second problem is more serious, that is, you cannot modify the status of subsequent tests and invalidate their results. You must ensure that the global status is reset to the status before the test is run. PHPUnit has some tools to help you back up global variables and restore their values after testing. These tools can help solve this problem. However, a better way is to enable the test class to pass the value of these global variables directly to the method. Listing 2 shows an example using this method.

Listing 2. modifying this function to support rewriting global variables

 
  

This not only makes the code more testable, but also makes it independent of the global variables of the method. This allows us to refactor the code without using global variables.

Single Instance that cannot be reset

A single instance refers to a class that allows an application to exist only one instance at a time. They are a common pattern used in applications for global objects, such as database connection and configuration settings. They are often considered as application taboos because many developers think that creating an always available object is of little use, so they do not pay too much attention to this. This problem is mainly caused by the excessive use of a single instance, because it will cause a large number of so-calledGod objects. But from the test perspective, the biggest problem is that they are usually unchangeable. Listing 3 is an example.

Listing 3. Singleton object to be tested

 
   

You can see that when a single instance is instantiated for the first timegetInstance()The method actually returns the same object. It does not create new objects. If we modify this object, it may cause serious problems. The simplest solution is to add a reset method to the object. Listing 4 shows an example.

Listing 4. added the Singleton object of the reset method.

 
    

Now, we can call the reset method before each test to ensure that the singleton object initialization code is executed during each test. In short, it is useful to add this method to an application, because we can now easily modify a single instance.

Use class Constructor

A good practice for unit testing is to test only the code to be tested and avoid creating unnecessary objects and variables. Each object and variable you create must be deleted after the test. This is a problem for troublesome projects such as files and database tables, because in these cases, if you need to modify the status, you must perform cleanup operations more carefully after the test is complete. The biggest obstacle to sticking to this rule lies in the constructor of the image itself. All operations it performs are irrelevant to the test. Listing 5 is an example.

Listing 5. classes with a large singleton Method

 
     results = $dbconn->query('select name from mytable');     }          public function getFirstResult()     {         return $this->results[0];     }  }

Here, to test the object'sfdfdfdFinally, we need to establish a database connection, add some records to the table, and then clear all these resources after the test. If you testfdfdfdThis process may be too complicated if you don't need it at all. Therefore, we need to modify the constructor shown in Listing 6.

Listing 6. Classes modified to ignore unnecessary initialization Logic

 
     init();     }          public function init()     {         $dbconn = new DatabaseConnection('localhost','user','password');         $this->results = $dbconn->query('select name from mytable');     }          public function getFirstResult()     {         return $this->results[0];     }  }

We have reconstructed a lot of code in the constructor and moved them toinit()Method, this method is still called by the constructor by default to avoid cracking the logic of the existing code. However, during the test, only one Boolean value false can be passed to the constructor to avoid callinginit()Method and all unnecessary initialization logic. Class refactoring also improves the code, because we separate the initialization logic from the object's constructor.

Hardcoded class dependency

As we described in the previous section, a large number of class design problems that cause difficulties in testing are concentrated on Initializing Various objects that do not need to be tested. Previously, we knew that the heavy initialization of the issue series could put a lot of burden on writing the test (especially when the test completely does not need these objects ), however, if we directly create these objects in the test class method, another problem may occur. Listing 7 shows the sample code that may cause this problem.

Listing 7. initialize the class of another object directly in one method

 
     query('select name from user');                  sort($results);                  return $results;     }  }

Suppose we are testing the abovegetUserListMethod, but our test focus is to ensure that the returned user list is sorted alphabetically. In this case, the question is not whether these records can be obtained from the database, because we want to test whether we can sort the returned records. The problem is that because we instantiate a database connection object in this method, we need to perform all these tedious operations to test the method. Therefore, we need to modify the method so that this object can be inserted in the middle, as shown in listing 8.

Listing 8. This class has a method that will directly instantiate another object, but it also provides an override method.

 
     query('select name from user');                  sort($results);                  return $results;     }  }

Now you can directly pass in an object that is compatible with the expected database connection object, and then directly use this object instead of creating a new object. You can also input a simulated object, that is, in some calling methods, the desired value is directly returned in hard-coded mode. Here, we can simulate the query method of the database connection object, so that we only need to return the results without actually querying the database. This method can also be improved when such refactoring is performed, because it allows your application to insert different database connections as needed, rather than binding only one specified default database connection.

Benefits of testable code

Obviously, writing more testable code can certainly simplify unit testing for PHP applications (as you can see in the example in this article), but in this process, it can also improve the design, modularity, and stability of applications. We have seen the "spaghetti" code, which is filled with a lot of business and performance logic in a major process of a PHP application, this will undoubtedly cause serious support problems for those who use this application. In the process of making the code more testable, We have reconstructed some of the previous problematic code, which is not only problematic in design but also functional. By making these functions and classes more widely used, and by removing hard-coded dependencies, we make them easier to be reused by other parts of the application, and we improve code reusability. In addition, we will replace poorly written code with better code to simplify future support for the code library.

Conclusion

In this article, we learned how to improve the testability of PHP code through some typical untestable code examples in PHP applications. We also introduced how these situations occur in the application, and then introduced how to properly fix these problems to facilitate testing. We also learned that the modifications to these Codes not only improve the Code testability, but also improve the quality of the Code and the reusability of the restructured code.

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.