How to develop a large PHP Project _ PHP Tutorial

Source: Internet
Author: User
Development of large PHP projects. The method for developing large PHP projects is described here in object-oriented programming (OOP, ObjectOrientedProgramming) in PHP ). I will show you how to use some OOP concepts and PHP skills to develop large PHP projects. here I will introduce object-oriented Programming (OOP, Object Oriented Programming) in PHP ). We will show you how to reduce coding and improve quality by using some OOP concepts and PHP skills. Good luck!

The concept of object-oriented programming:
Different authors may have different ideas, but an OOP language must have the following aspects:

Abstract data types and information encapsulation
Inheritance
Polymorphism

In PHP, classes are encapsulated:

Code:

Class Something {
// In The OOP class, the first character is usually uppercase.
Var $ x;
Function setX ($ v ){
// The method starts with lowercase words, and then uses uppercase letters to separate words, such as getValueOfArea ()
$ This-> x = $ v;
}
Function getX (){
Return $ this-> x;
}
}
?>



Of course, you can define it according to your preferences, but it is better to maintain a standard to make it more effective.

Data members are defined using the "var" declaration in the class. they have no type before assigning values to data members. A data member can be an integer, an array, an associated array, or an object.

A method is defined as a function in a class. when using a member variable of the class in a method, you should use $ this-> name. Otherwise, a method can only be a local variable.

Use the new operator to create an object:

$ Obj = new Something;

Then you can use the member function to pass:

$ Obj-> setX (5 );
$ See = $ obj-> getX ();

In this example, the setX member function assigns 5 to the object's member variable x (not a class), and then getX returns its value 5.

You can access data members by referencing classes like $ obj-> x = 6. this is not a good OOP habit. I strongly recommend that you use methods to access member variables. If you think of member variables as unmanageable and use methods only through object handles, you will be a good OOP programmer. Unfortunately, PHP does not support declaring private member variables, so bad code is also allowed in PHP.

Inheritance is easy to implement in PHP, as long as the extend keyword is used.

Code:

Class Another extends Something {
Var $ y;
Function setY ($ v ){
$ This-> y = $ v;
}
Function getY (){
Return $ this-> y;
}
}
?>



The object of the "Another" class now has all the data members and methods of the parent class (Something), and adds its own data members and methods.

You can use

Code:

$ Obj2 = new Something;
$ Obj2-> setX (6 );
$ Obj2-> setY (7 );



PHP currently does not support multi-inheritance, so you cannot derive a new class from two or more classes.

You can redefine a method in a derived class. if we redefine the getX method in the "Another" class, we cannot use the getX method in "Something. If you declare a data member with the same name as the base class in the derived class, it will "hide" the data member of the base class when you process it.

You can define constructors in your class. A constructor is a method with the same name as a class name. it is called when you create a class object. for example:

Code:

Class Something {
Var $ x;
Function Something ($ y ){
$ This-> x = $ y;
}
Function setX ($ v ){
$ This-> x = $ v;
}
Function getX (){
Return $ this-> x;
}
}
?>



Therefore, you can create an object:

$ Obj = new Something (6 );

The constructor automatically assigns value 6 to the data variable x. Constructors and methods are common PHP functions, so you can use the default parameters.

Function Something ($ x = "3", $ y = "5 ")

Next:

$ Obj = new Something (); // x = 3 and y = 5
$ Obj = new Something (8); // x = 8 and y = 5
$ Obj = new Something (8, 9); // x = 8 and y = 9

The default parameter uses the C ++ method, so you cannot ignore the value of Y. Instead, assign a value to X from left to right, if the input parameter is less than the required parameter, the default parameter is used for the input parameter.

When an object of a derived class is created, only its constructor is called, and the constructor of the parent class is not called. if you want to call the constructor of the base class, you must display the call in the constructor of the derived class. This can be done because all methods of the parent class in the derived class are available.

Code:

Function Another (){
$ This-> y = 5;
$ This-> Something ();
// Display the call base class constructor
}
?>



A good mechanism of OOP is to use abstract classes. Abstract classes cannot be instantiated and can only be provided to an interface of the derived class. Designers usually use abstract classes to force programmers to derive from the base class. This ensures that the new class contains some expected functions. There is no standard method in PHP,:

If you need this feature, you can define the base class and add the "die" call to its constructor to ensure that the base class cannot be instantiated, now, the "die" statement is added after each method (interface). Therefore, if a programmer does not overwrite the method in the derived class, an error is thrown. And because PHP is non-typed, you may need to confirm that an object comes from the derived class of your base class, then add a method to the base class to implement the class identity (return a certain id), and verify this value when you receive an object parameter. Of course, if an evil and bad programmer overwrites this method in a derived class, this method does not work, but generally the problem occurs frequently in the lazy programmer, rather than the evil programmer.

Of course, it is good to make the base class invisible to programmers, as long as the interface is printed out for their work.

No Destructor in PHP.

Overload (different from overwriting) is not supported in PHP. In OOP, you can overload a method to implement two or more methods with the same name, but there are different numbers or types of parameters (depending on the language ). PHP is a loose language, so the type overload does not work, but the overload does not work by the number of parameters.

Sometimes the overload constructor in OOP is very good, so that you can create objects using different methods (passing different numbers of parameters ). In PHP
To implement it:

Code:

Class Myclass {
Function Myclass (){
$ Name = "Myclass". func_num_args ();
$ This-> $ name ();
// Note that $ this-> name () is generally incorrect, but $ name is the name of the method to be called.
}
Function Myclass1 ($ x ){
Code;
}
Function Myclass2 ($ x, $ y ){
Code;
}
}
?>



Through additional processing in the class, using this class is transparent to users:

$ Obj1 = new Myclass ('1'); // call Myclass1

$ Obj2 = new Myclass ('1', '2'); // call Myclass2

Sometimes this is very useful.

Polymorphism
Polymorphism is a capability of an object. it determines the method of the object to be called at runtime based on the passed object parameters. For example, if you have a figure class, it defines a draw method. The circle and rectangle classes are derived. in the derived class, you overwrite the draw method. you may also have a function that uses the x parameter, you can call $ x-> draw (). If you have polymorphism, the draw method that you call depends on the object type that you pass to this function.

Polymorphism is in an interpreted language like PHP (imagine which method should you call when a C ++ compiler generates such code? You don't know what type of objects you have. well, this is not the point.) it is very easy and natural. Therefore, PHP certainly supports polymorphism.

Code:

Function niceDrawing ($ x ){
// Assume this is a method of the Board class.
$ X-> draw ();
}
$ Obj = new Circle (3,187 );
$ Obj2 = new Rectangle (4, 5 );
$ Board-> niceDrawing ($ obj );
// Call the draw method of Circle
$ Board-> niceDrawing ($ obj2 );
// Call the draw method of Rectangle
?>



Use PHP for object-oriented programming
Some purists may say that PHP is not a real object-oriented language. PHP is a hybrid language. you can use OOP or traditional procedural programming. However, for large projects, you may want/need to use pure OOP to declare classes in PHP, and only use objects and classes in your project.

As the project grows, it may be helpful to use OOP, and the OOP code is easy to maintain, easy to understand and reuse. These are software engineering.
. Applying these concepts in web-based projects will become the key to future website success.

PHP advanced OOP technology
After reading the basic OOP concepts, I can show you more advanced technologies:

Serializing)
PHP does not support permanent objects. in OOP, permanent objects are objects that can maintain the state and function in the references of multiple applications, this means that you have the ability to save objects to a file or database and can load objects later. This is the so-called serialization mechanism. PHP has a serialization method, which can be called through an object. the serialization method can return the string representation of an object. However, serialization only saves the member data of the object without the package method.

In PHP4, if you serialize an object to the string $ s, release the object, and deserialize the object to $ obj, you can continue to use the object method! I do not recommend that you do this because (a) the document does not guarantee that this behavior can still be used in future versions. (B) this may lead to a misunderstanding when you save a serialized version to the disk and exit the script. When you run this script in the future, you cannot expect that when deserializing an object, the object method will also be there, because the string representation does not include the method at all.

All in all, PHP Serialization is very useful for saving object member variables. (You can also serialize related arrays and arrays to a file ).

Example:

Code:

$ Obj = new Classfoo ();
$ Str = serialize ($ obj );
// A few months later
// Input str from the disk
$ Obj2 = unserialize ($ str)
?>



You have recovered the member data, but do not include methods (as described in this document ). As a result, you can only use $ obj2-> x to access member variables (you have no other way !) So do not try it at home.

There are some ways to solve this problem. I keep it because they are too bad for this concise article.

Use Classes for data storage
A good thing for PHP and OOP is that you can easily define a class to operate on something and call the corresponding class whenever you want to use it. Suppose you have an HTML form. you can select a product by selecting the product ID. There is product information in the database. you want to display the product and its price. You have different types of products, and the same action may have different meanings for different products. For example, displaying a sound may mean playing it, but for other products, it may mean displaying an image in the database. You can use OOP or PHP to reduce coding and improve quality:

Define a product class, define its expected method (for example, display), and then define the class of each type of product, which is sent from the product class (SoundItem class, viewableItem class, etc.), overwrite the methods in the product class, and make them act as you want.

Name the class according to the type field of each product in the database. a typical product table may have (id, type, price, description, and other fields )... in the processing script, you can retrieve the type value from the database and instantiate an object named type:


Code:

$ Obj = new $ type ();
$ Obj-> action ();
?>



This is a very good feature of PHP. you can call the $ obj display method or other methods without considering the object type. With this technology, you do not need to modify the script to add a new type of object, but add a class to process it.

This function is very powerful, as long as you define methods, instead of considering the types of all objects, implement them in different classes according to different methods, and then use them for any objects in the main script, no if... else, there is no need for two programmers, just happy.

Now you agree that programming is easy, maintenance is cheap, and reusable is true?

If you manage a group of programmers, it is very easy to assign jobs. each person may be responsible for a type of object and the class that processes it.

You can use this technology to achieve internationalization and apply the corresponding classes based on the language fields selected by the user.


Copy and clone
When you create a $ obj object, you can use $ obj2 = $ obj to copy the object. The new object is a copy of $ obj (not a reference ), therefore, it has the status of $ obj at that time. Sometimes, you just want to generate a new object like the obj class. you can use the new statement to call the class constructor. PHP can also be implemented through serialization and a base class, but all other classes must be derived from the base class.


Enter Dangerous area
When you serialize an object, you will get a string of a certain format. if you are interested, you can call it. among them, there is a class name in the string (great !), You can take it out, such:

Code:

$ Herring = serialize ($ obj );
$ Vec = explode (':', $ herring );
$ Nam = str_replace ("\" ",'', $ vec [2]);
?>



So suppose you have created a "Universe" class and forced all classes to be extended from universe. you can define a clone method in universe, as shown below:

Code:

Class Universe {
Function clone (){
$ Herring = serialize ($ this );
$ Vec = explode (':', $ herring );
$ Nam = str_replace ("\" ",'', $ vec [2]);
$ Ret = new $ nam;
Return $ ret;
}
}
// Then
$ Obj = new Something ();
// Extend from Universe
$ Other = $ obj-> clone ();
?>



What you get is a new Something Class object, which is the same as the object created by calling the constructor using the new method. I don't know if this is useful to you, but the Universe class can know that the name of a derived class is a good experience. Imagination is the only restriction. (Source: Flash)

Define (OOP, Object Oriented Programming ). I will show you how to use some OOP concepts and PHP skills...

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.