In the PHPV5 Migration Guide, read the PHPV5 Migration Guide and use the new language features of PHPV5 to significantly improve code maintainability and reliability. By reading this article, you will learn how to use these new features to migrate code developed with PHPV4 to phpv5. PHPV5 has made significant improvements based on PHPV4. New language features allow building a reliable class library "> <LINKhref
Using the new language features of PHP V5 can significantly improve the maintainability and reliability of code. By reading this article, you will learn how to use these new features to migrate code developed with PHP V4 to PHP V5.
PHP V5 has made major improvements based on PHP V4. New language features make it easier to build reliable class libraries and maintain class libraries. In addition, rewriting the standard library helps make PHP more compliant with the same Web language, such as the Java™ programming language. Let's take a look at some new PHP object-oriented features and learn how to migrate existing PHP V4 code to PHP V5.
First, let's first understand the features of the new language and how the PHP creation program has changed the method for creating objects using PHP V4. The idea of using V5 is to create an industrial language for Web application development. That means you need to understand the limits of PHP V4 and then learn from other languages (such as Java, C #, C ++, Ruby, and Perl) extract known and outstanding language architectures and integrate these architectures into PHP.
The first and most important new feature is the access protection for class methods and instance variables-public, protected, and private keywords. This new feature allows the class designer to ensure control over the internal characteristics of the class, and also tells the class users which classes can and which classes cannot be touched.
In PHP V4, all code is public. In PHP V5, class designers can declare which code is externally visible (public) and which code is only visible (private) to the class) or only visible to the subclass of the class (protected ). Without such access control, the development of code in a large team or the distribution of code as a library will be blocked, because users of those classes are likely to use incorrect methods or access code that should be private member variables.
Another major new feature is the keyword interface and abstract, which allow contract programming. Contract programming means that one class provides a contract to another class-in other words: "This is what I want to do, and you don't need to know how it is done ". All classes implementing the interface follow this contract. All users of the interface agree to use only the methods specified in the interface. Abstract keywords make it easy to use interfaces. I will describe them later.
These two main features-access control and contractual programming-allow large coding teams to use large code libraries more smoothly. These features also enable IDE to provide a richer set of intelligent language features. This article not only illustrates several migration issues, but also takes some time to explain how to use these new main language features.
Access control
To demonstrate the features of the new language, I used a class named Configuration. This simple class contains configuration items for Web applications-for example, the path to the image directory. Ideally, this information will be stored in a file or database. Listing 1 shows a simplified version.
Listing 1. access. php4
Class Configuration
{
Var $ _ items = array ();
Function Configuration (){
$ This-> _ items ['imgpath'] = 'images ';
}
Function get ($ key ){
Return $ this-> _ items [$ key];
}
}
$ C = new Configuration ();
Echo ($ c-> get ('imgpath'). "\ n ");
?>
This is a fully Orthodox PHP V4 class. The member variables save the list of configuration items, construct the loaded items of the program, and then return the value of the access method named get.
After running the script, the following code is displayed in the command line:
% Php access. php4
Images
%
Good! This result indicates that the code runs normally and the imgpath configuration item value is set and read normally.
The first step to convert this class to PHP V5 is to rename the constructor. In PHP V5, the initialization object (constructor) method is called _ construct. This small change is as follows.
Listing 2. access1.php5
Class Configuration
{
Var $ _ items = array ();
Function _ construct (){
$ This-> _ items ['imgpath'] = 'images ';
}
Function get ($ key ){
Return $ this-> _ items [$ key];
}
}
$ C = new Configuration ();
Echo ($ c-> get ('imgpath'). "\ n ");
?>
This change is not significant. Just move to the PHP V5 convention. The next step is to add access control to the class to ensure that the class user cannot directly read and write the $ _ items member variable. The change is as follows.
Listing 3. access2.php5
Class Configuration
{
Private $ _ items = array ();
Public function _ construct (){
$ This-> _ items ['imgpath'] = 'images ';
}
Public function get ($ key ){
Return $ this-> _ items [$ key];
}
}
$ C = new Configuration ();
Echo ($ c-> get ('imgpath'). "\ n ");
?>
If the user of this object needs to directly access the item array, access will be denied because the array is marked as private. Fortunately, the user found that the get () method can provide a wide range of popular read permissions.
To demonstrate how to use the protected permission, I need another class that must inherit from the Configuration class. I call that class DBConfiguration and assume that the class will read the configuration value from the database. This setting is as follows.
Listing 4. access3.php
Class Configuration
{
Protected $ _ items = array ();
Public function _ construct (){
$ This-> load ();
}
Protected function load (){}
Public function get ($ key ){
Return $ this-> _ items [$ key];
}
}
Class DBConfiguration extends Configuration
{
Protected function load (){
$ This-> _ items ['imgpath'] = 'images ';
}
}
$ C = new DBConfiguration ();
Echo ($ c-> get ('imgpath'). "\ n ");
?>
This list shows the correct use of the protected keyword. The base class defines a method named load. This subclass overwrites the load () method to add data to the items table. The load () method is an internal method for the class and its subclass. Therefore, this method is invisible to all external users. If all keywords are private, the load () method cannot be overwritten.
I don't like this design very much, but I chose it because the DBConfiguration class must be able to access the item array. I want to continue to use the Configuration class to fully maintain the item array so that after other subclasses are added, those classes do not need to know how to maintain the item array. I made the following changes.
Listing 5. access4.php5
Class Configuration
{
Private $ _ items = array ();
Public function _ construct (){
$ This-> load ();
}
Protected function load (){}
Protected function add ($ key, $ value ){
$ This-> _ items [$ key] = $ value;
}
Public function get ($ key ){
Return $ this-> _ items [$ key];
}
}
Class DBConfiguration extends Configuration
{
Protected function load (){
$ This-> add ('imgpath', 'images ');
}
}
$ C = new DBConfiguration ();
Echo ($ c-> get ('imgpath'). "\ n ");
?>
Now, the item array can be private, because the subclass uses the protected add () method to add the configuration item to the list. The Configuration class can change the method for storing and reading Configuration items without considering its subclass. As long as the load () and add () methods run in the same way, the subclass should not have problems.
For me, adding access control is the main reason to consider moving to PHP V5. Is it because Grady Booch says PHP V5 is one of the four object-oriented languages? No, because I used to accept a task to maintain the 100 KLOC C ++ code, in which all methods and members are defined as public. It took me three days to clear these definitions and significantly reduced the number of errors and increased maintainability. Why? Without access control, it is impossible to know how objects use other objects, and to make any changes without knowing what difficulties to break through. With C ++, at least I still have compilation programs available. PHP is not equipped with a compilation program, so this type of access control becomes increasingly important.
Contract Programming
When migrating from PHP V4 to PHP V5, the next important feature is to support contractual programming through interfaces, abstract classes, and methods. Listing 6 shows a version of the Configuration class. In this class, PHP V4 coders try to build the basic interface without using the interface keyword.
Listing 6. interface. php4
Class IConfiguration
{
Function get ($ key ){}
}
Class Configuration extends IConfiguration
{
Var $ _ items = array ();
Function Configuration (){
$ This-> load ();
}
Function load (){}
Function get ($ key ){
Return $ this-> _ items [$ key];
}
}
Class DBConfiguration extends Configuration
{
Function load (){
$ This-> _ items ['imgpath'] = 'images ';
}
}
$ C = new DBConfiguration ();
Echo ($ c-> get ('imgpath'). "\ n ");
?>
The list starts with a small IConfiguration class that defines the interfaces provided by all Configuration classes or derived classes. This interface defines the contract between the class and all its users. The contract declares that all classes implementing IConfiguration must be equipped with the get () method, and all users of IConfiguration must insist that only the get () method is used.
The following code runs in PHP V5, but it is best to use the provided interface system, as shown below.
Listing 7. interface1.php5
Interface IConfiguration
{
Function get ($ key );
}
Class Configuration implements IConfiguration
{
...
}
Class DBConfiguration extends Configuration
{
...
}
$ C = new DBConfiguration ();
Echo ($ c-> get ('imgpath'). "\ n ");
?>
On the one hand, readers can better understand the running status; on the other hand, a single class can implement multiple interfaces. Listing 8 shows how to extend the Configuration class to implement the Iterator interface. For PHP, this interface is an internal interface.
Listing 8. interface2.php5
Interface IConfiguration {
...
}
Class Configuration implements IConfiguration, Iterator
{
Private $ _ items = array ();
Public function _ construct (){
$ This-> load ();
}
Protected function load (){}
Protected function add ($ key, $ value ){
$ This-> _ items [$ key] = $ value;
}
Public function get ($ key ){
Return $ this-> _ items [$ key];
}
Public function rewind () {reset ($ this-> _ items );}
Public function current () {return current ($ this-> _ items );}
Public function key () {return key ($ this-> _ items );}
Public function next () {return next ($ this-> _ items );}
Public function valid () {return ($ this-> current ()! = False );}
}
Class DBConfiguration extends Configuration {
...
}
$ C = new DBConfiguration ();
Foreach ($ c as $ k = >$ v) {echo ($ k. "=". $ v. "\ n ");}
?>
The Iterator interface allows all classes to appear as arrays of their users. As you can see at the end of the script, you can use the foreach operator to reiterate all Configuration items in the Configuration object. PHP V4 does not provide this function, but you can use it in various ways in the application.
The advantage of the interface mechanism is that the contract can be quickly integrated without any method. The final stage is the implementation interface. You must implement all the specified methods. Another helpful new function in PHP V5 is the abstract class. Using the abstract class, you can easily use a base class to implement the core part of the interface, and then use this interface to create an object class.
Another purpose of an abstract class is to create a base class for multiple derived classes. In these derived classes, the base class will never be instantiated. For example, if both DBConfiguration and Configuration exist, you can only use DBConfiguration. The Configuration class is just a base class-an abstract class. Therefore, you can use the abstract keyword to force this behavior, as shown below.
Listing 9. abstract. php5
Abstract class Configuration
{
Protected $ _ items = array ();
Public function _ construct (){
$ This-> load ();
}
Abstract protected function load ();
Public function get ($ key ){
Return $ this-> _ items [$ key];
}
}
Class DBConfiguration extends Configuration
{
Protected function load (){
$ This-> _ items ['imgpath'] = 'images ';
}
}
$ C = new DBConfiguration ();
Echo ($ c-> get ('imgpath'). "\ n ");
?>
Now, all attempts to instantiate Configuration objects will fail, because the system considers the class abstract and incomplete.
Static methods and members
Another important new function in PHP V5 is to support using static members and methods for classes. With this feature, you can use the popular Singleton mode. This mode is ideal for the Configuration class, because the application should have only one Configuration object.
Listing 10 shows the Configuration class of PHP V5 as a singleton.
Listing 10. static. php5
Class Configuration
{
Private $ _ items = array ();
Static private $ _ instance = null;
Static public function get (){
If (self: $ _ instance = null)
Self: $ _ instance = new Configuration ();
Return self: $ _ instance;
}
Private function _ construct (){
$ This-> _ items ['imgpath'] = 'images ';
}
Public function _ get ($ key ){
Return $ this-> _ items [$ key];
}
}
Echo (Configuration: get ()-> {'imgpath'}. "\ n ");
?>
There are many usage of static keywords. Use this keyword to access some global data of all objects of a single type.
Magic Method
Another major new feature in PHP V5 is the support for magic methods, which allows an object to quickly change its interface-for example, adding a member variable for each Configuration item in the Configuration object. You don't need to use the get () method. You just need to find a special item and treat it as an array, as shown below.
Listing 11. magic. php5
Class Configuration
{
Private $ _ items = array ();
Function _ construct (){
$ This-> _ items ['imgpath'] = 'images ';
}
Function _ get ($ key ){
Return $ this-> _ items [$ key];
}
}
$ C = new Configuration ();
Echo ($ c-> {'imgpath'}. "\ n ");
?>
In this example, I created a new _ get () method, which is called when the user looks for the member variables on the object. Then, the code in the method will use the item array to find the value and return the value, just as there is a member variable dedicated to this keyword. Assuming that the object is an array, at the end of the script, you can see that using the Configuration object is as simple as searching for imgpath values.
When migrating from PHP V4 to PHP V5, you must pay attention to these language features that are completely unavailable in PHP V4, and re-verify the class to see how these classes can be used.
Exception
Finally, we will introduce the new exception mechanism in PHP V5 to end this article. Exception provides a completely new method for considering error handling. All programs inevitably generate errors, such as file not found and insufficient memory. If no exception is used, the error code must be returned. See the following PHP V4 code.
Listing 12. file. php4
Function parseLine ($ l)
{
//...
Return array ('error' => 0,
Data => array () // data here
);
}
Function readConfig ($ path)
{
If ($ path = null) return-1;
$ Fh = fopen ($ path, 'r ');
If ($ fh = null) return-2;
While (! Feof ($ fh )){
$ L = fgets ($ fh );
$ Ec = parseLine ($ l );
If ($ ec ['error']! = 0) return $ ec ['error'];
}
Fclose ($ fh );
Return 0;
}
$ E = readConfig ('myconfig.txt ');
If ($ e! = 0)
Echo ("There was an error (". $ e. ") \ n ");
?>
The standard file I/O code reads a file, retrieves some data, and returns the error code in case of any errors. I have two questions about this script. The first is the error code. What are the meanings of these error codes? To find out the meaning of these error codes, you must create another system to map these error codes to meaningful strings. The second problem is that the returned results of parseLine are very complex. I only need it to return data, but it must actually return error code and data. Most engineers (including myself) are often lazy and return only data, ignoring errors because they are difficult to manage.
Listing 13 shows how clear code is when exceptions are used.
Listing 13. file. php5
Function parseLine ($ l)
{
// Parses and throws and exception when invalid
Return array (); // data
}
Function readConfig ($ path)
{
If ($ path = null)
Throw new Exception ('bad argument ');
$ Fh = fopen ($ path, 'r ');
If ($ fh = null)
Throw new Exception ('could not open file ');
While (! Feof ($ fh )){
$ L = fgets ($ fh );
$ Ec = parseLine ($ l );
}
Fclose ($ fh );
}
Try {
ReadConfig ('myconfig.txt ');
} Catch (Exception $ e ){
Echo ($ e );
}
?>
I don't need to worry about the error code because the exception contains incorrect descriptive text. I also don't need to consider how to trace the error code returned from parseLine, because if an error occurs, this function will throw only one error. The stack will extend to the nearest try/catch block, which is located at the bottom of the script.
The exception mechanism will completely change the code writing method. You don't have to manage headache error codes and mappings, so you can focus on the errors to be handled. This code is easier to read and maintain, and I would like to say that you should be encouraged to add an error handling mechanism, which usually brings benefits.
Conclusion
The addition of new object-oriented features and exception handling provides a strong reason to migrate code from PHP V4 to PHP V5. As you can see, the upgrade process is not difficult. The syntax for extending to PHP V5 is like PHP. Yes, these syntaxes come from languages such as Ruby, but I think they work very well together. These languages also extend the scope of PHP from a scripting language for small sites to a language for enterprise-level applications.