Ways to develop large PHP projects _php Abstracts

Source: Internet
Author: User
Tags explode extend html form inheritance php and serialization
Ways to develop a large PHP project 1

This article describes object-oriented programming in PHP (Oop,object oriented programming). I'll show you how to reduce coding and improve quality by using some OOP concepts and PHP techniques. Good luck!



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

Abstract data types and information encapsulation

Inherited

Polymorphic


The encapsulation is done in PHP by a class:

---------------------------------------------------

Class Something {

In an OOP class, the first character is usually uppercase

var $x;

function SetX ($v) {

Method starts with a lowercase word and then uses uppercase letters to separate words, such as Getvalueofarea ()

$this->x= $v;


}


function GetX () {


return $this->x;


}


}


?>---------------------------------------------------

Of course you can define your own preferences, but it's best to keep a standard, which is more effective.


Data members are defined in a class using the "var" declaration, which is not typed until the data member is assigned a value. A data member can

To be an integer, an array, an associated array (associative array), or an object.


method is defined as a function form in a class, you should use $this->name when accessing a class member variable in a method, otherwise it can only be a local variable for a method.


To create an object using the new operator:
$obj =new something;

You can then use the member function to pass:

$obj->setx (5);

$see = $obj->getx ();


In this example, the SETX member function assigns 5 to the member variable X (not the Class) of the object, and then Getx returns its value of 5.


It is not a good OOP habit that you can access data members in the same way as $obj->x=6 through a class reference. I strongly recommend using methods to access member variables. You would be a good OOP programmer if you think of the member variables as not being handled and use the method only through the object handle. Unfortunately, PHP does not support declaring private member variables, so bad code is also allowed in PHP.

Inheritance is easy to implement in PHP, just use the Extend keyword.

-----------------------------------------------------
Class Another extends something {


var $y;


function Sety ($v) {


$this->y= $v;


}


function GetY () {

return $this->y;

}


}


?>
Ways to develop large PHP projects (2)

Objects in the "Another" class now have all the data members and methods of the parent class (something), plus their own data members and methods.

You can use

$obj 2=new something;

$obj 2->setx (6);

$obj 2->sety (7);

PHP does not now support multiple inheritance, so you cannot derive new classes from two or more than two classes.


You can redefine a method in a derived class, and if we redefine the Getx method in the "Another" class, we can't use the Getx method in "something". If you declare a data member with the same name as Kippe in a derived class, it will "hide" the data members of the base class when you process it.

You can define constructors in your class. A constructor is a method that has the same name as a class name and is invoked when you create an object of a class, for example:


-----------------------------------------------------
Class Something {

var $x;


function something ($y) {

$this->x= $y;

}

function SetX ($v) {

$this->x= $v;

}


function GetX () {

return $this->x;


}


}

?>---------------------------------------------------

So you can create an object by:

$obj =new Something (6);

The constructor automatically assigns a value of 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")

Then:

$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 C + +, so you can't ignore the value of Y, and give X a default parameter, which is assigned from left to right, if

When the parameters passed in are less than the required parameters, they will use the default parameters.


When an object of a derived class is created, only its constructor is invoked, and the constructor of the parent class is not invoked, if you want to call the base

class, you must display the call in the constructor of the derived class. You can do this because the methods of all the parent classes in a derived class are available.


-----------------------------------------------------

function Another () {


$this->y=5;

$this->something ();

Show call base class constructor

}


?>---------------------------------------------------

An excellent mechanism for OOP is to use abstract classes. An abstract class is not instantiated and can only be supplied to a derived class as an interface. Designers often use abstract classes to force programmers to derive from a base class, which ensures that the new class contains some expected functionality. There are no standard methods in PHP, but:


If you need this feature, you can define the base class, and adding "die" to its constructor, which guarantees that the base class is not instantiated and now adds the "die" statement after each method (interface), so if a programmer does not overwrite the method in the derived class, an error is raised. And because PHP is untyped, you may need to verify that an object is derived from your base class, add a method to the base class's identity (return some identity id), and validate the value when you receive an object parameter. Of course, if an evil-bad programmer overrides this method in a derived class, this approach will not work, but the general problem is more of an idle programmer than an evil one.


Of course, it's nice to be able to make the base class impossible for programmers to see, just print the interface to do their job.


There are no destructors in PHP.
Ways to develop large PHP projects (3)

Overloading (unlike overlay) is not supported in PHP. In OOP, you can overload a method to implement two or more methods with the same name, but with different numbers or types of arguments (which depends on the language). PHP is a loosely typed language, so it does not work through type overloading, but overloading does not work with different numbers of arguments.

Sometimes overloading constructors in OOP is great, so you can create objects in different ways (passing a different number of arguments). The trick to implementing it in PHP is:

--------------------------------------
Class Myclass {

function Myclass () {
$name = "Myclass". Func_num_args ();

$this-> $name ();

Note that $this->name () is generally wrong, but here $name is the name of the method to be invoked

}

function Myclass1 ($x) {

Code

}
function Myclass2 ($x, $y) {

Code

}

}

?>

Using this class is transparent to the user through additional processing in the class:


$obj 1=new Myclass (' 1 '); Will call Myclass1

$obj 2=new Myclass (' 1 ', ' 2 '); Will call Myclass2

Sometimes this is very useful.


Polymorphic

Polymorphism is the ability of an object to decide which object to invoke, based on the parameters of the object passed at run time. For example, if you have a figure class, it defines a draw method. and derive the circle and rectangle classes, in which you override the Draw method, you might also have a function that expects to use a parameter X and can call $x->draw (). If you have polymorphism, calling which draw method depends on the type of object you pass to the function.


Polymorphism in an interpreted language like PHP (imagine a C + + compiler generating such code, which method should you call?) You also don't know what type of object you have, OK, that's not the point, it's very easy and natural. So PHP certainly supports polymorphism.

-----------------------------------------------------
function nicedrawing ($x) {

Suppose this is a method of the Board class

$x->draw ();

}

$obj =new Circle (3,187);

$obj 2=new Rectangle (4,5);

$board->nicedrawing ($obj);

The draw method that will invoke circle

$board->nicedrawing ($obj 2);

The draw method that will invoke rectangle

?>



Object-oriented Programming with PHP

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

As the project grows, using OOP can be helpful, and OOP code is easy to maintain, easy to understand and reuse. These are the foundations of software engineering. Applying these concepts to web-based projects is the key to success in future Web sites.


Advanced OOP techniques in PHP

After looking at basic OOP concepts, I can show you more advanced technologies:

Serialization (serializing)

PHP does not support persistent objects, where permanent objects are objects that can maintain state and functionality in multiple application references, which means that you have the ability to save objects to a file or database, and you can load objects later. This is called the serialization mechanism. PHP has a serialization method that can be invoked through objects, and the serialization method can return the string representation of an object. However, serialization saves only the member data of the object without wrapping the method.

In PHP4, if you serialize an object into a string $s, then release the object and then deserialize the object to $obj, you can continue using the object's Method! I do not recommend doing this because (a) there is no guarantee in the document that this behavior can still be used in future releases. (b) This may lead to a misunderstanding when you save a serialized version to disk and exit the script. When you run this script later, you can't expect the object's method to be there when you deserialize an object, because the string representation does not include the method at all.

In summary, the serialization of PHP is useful for saving the member variables of an object. (You can also serialize related arrays and arrays to a file).

Example:
-----------------------------------------------------
$obj =new Classfoo ();

$str =serialize ($obj);

Save $str to disk

A few months later

Mount Str from disk

$obj 2=unserialize ($STR)

?>---------------------------------------------------

You have restored the member data, but not the method (according to the document). This leads to access to member variables only by using $obj2->x (you have no other way!). The only way, so don't try it at home.

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

I would be happy to welcome the full serialization feature in subsequent versions of PHP.
Ways to develop large PHP projects (4)

Using classes for data storage

A great thing about PHP and OOP is that you can easily define a class to manipulate something, and you can call the class whenever you want to use it. If you have an HTML form, the user can select a product by selecting the Product ID number. In the database has the product information, you want to display the product, displays its price and so on. You have different types of products, and the same action may have different meanings for different products. For example, displaying a sound might mean playing it, but for other kinds of products it might mean displaying a picture in a database. You can use OOP or PHP to reduce coding and improve quality:

Define a product's class, define the methods it should have (for example: Display), and then define the classes for each type of product, from the Product class Pie (Sounditem class, Viewableitem class, etc.), and cover the methods in the product class so that they act as you think.


A typical product table may have (ID, type, price,description, etc. fields) according to the Type field of each product in the database. Then in the processing script, you can take the type value out of the database and instantiate an object named type:

--------------------------------
$obj =new $type ();

$obj->action ();

?>

This is a very good feature of PHP, you can call the $obj display method or other method without considering the type of object. With this technique, you don't need to modify the script to add a new type of object, just add a class that handles it.


This is a powerful feature, as long as you define the method without considering the types of all the objects, implement them in different ways in different classes, and then use them in the main script for any object, no if...else, no two programmers, just be happy.


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

If you manage a group of programmers, assigning work is simple, and each person may be responsible for one type of object and the class that handles it.


You can internationalize through this technology, apply the appropriate classes to the language fields that the user chooses, and so on.



Copy and Clone
When you create a $obj object, you can copy the object by $obj2= $obj, and the new object is a copy of $obj (not a reference), so it has $obj state at the time. Sometimes you don't want to, you just want to generate a new object like the Obj class, you can invoke the constructor of the class by using the new statement. It can also be done in PHP by serialization, and a base class, but all the other classes derive from the base class.




Enter the danger zone.

When you serialize an object, you get a string of some form, and if you're interested, you can tune it, where the string has the name of the class (great!). ), you can take it out like this:

----------------------------------------
$herring =serialize ($obj);

$vec =explode (': ', $herring);

$nam =str_replace ("" ",", $vec [2]);
?>


So suppose you create a "universe" class and force all classes to extend from universe, you can define a clone in universe, as follows:

-----------------------------------
Class Universe {

function Clone () {

$herring =serialize ($this);

$vec =explode (': ', $herring);

$nam =str_replace ("" ",", $vec [2]);

$ret =new $nam;
return $ret;

}

}
And then
$obj =new something ();


Extending from Universe
$other = $obj->clone ();

?>

What you get is a new something class object that uses the same object that the constructor creates by using the new method. I don't know if this works for you, but the Universe class can know the name of a derived class is a good experience. Imagination is the only limit.

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.