Object-oriented advantages of PHP database operations

Source: Internet
Author: User
Tags php database


We all know how to obtain the required rows (Records) from MySQL, read the data, and then access some changes. Obviously, it is also very direct, and there is nothing behind this process. However Program When designing (OOP) to manage data in our database, this process needs to be greatly improved. This article Article A simple description of how to design an object-oriented method to manage database records. All internal logical relationships in your data will be encapsulated into a very organized record object, which can provide dedicated (dedicated) Validation Code System, conversion, and data processing. With the release of Zend engine2 and PhP5, PHP developers will have more powerful object-oriented tools to assist in their work, which will make the process (in the face of Object-based database management) more attractive.

The following lists some useful aspects of using objects to describe your database:

The access method (accessor methods) gives you full control over the Read and Write processes of attributes.
Each record and attribute (operation) at each level has a validation process.
Intelligently retrieve objects from Relational Tables
The repeated logic method means that all data interaction is performed through the same basic code (codebase), which makes maintenance easier.
The code is simple, because the internal logic of different records is already included in their own classes, rather than the tedious Library (LIB) file.
When you manually write code and SQL query statements, fewer errors may occur.

Accessor methods)

The access method is to assign values to the variables of an instance through a class. For example, I have a class named user and an instance $ username. I will write such an access method (function), user-> username () and user-> setusername () are used to return and assign values to instances.

<? PHP
Class user {
VaR $ username;

Function username (){
Return $ this-> username;
}

Function setusername ($ newusername ){
$ This-> username = $ newusername;
}
}
?>

There is a good reason for us to write such "special code ". It will make the developer more flexible to change the tedious work of the class, because this process will not require other PHP code using the class. Let's take a look at the more comprehensive and trustworthy user class below.

The variable $ username will no longer exist, and everything will be integrated into the array $ _ data.
If username is empty, the username () function provides a default value to it.
The setusername () process will confirm whether the username complies with the standard format (such as the font length) before accepting the value)

<? PHP
Class user {
VaR $ _ DATA = array (); // associative array containing all the attributes for the user

Function username (){
Return! Empty ($ this-> _ DATA ['username'])? $ This-> _ DATA ['username']: '(no name !) ';
}

Function setusername ($ newusername ){
If ($ this-> validateusername ($ newusername )){
$ This-> _ DATA ['username'] = $ newusername;
}
}

Function validateusername (& $ somename ){
If (strlen ($ somename)> 12 ){
Throw new exception ('your username is too long'); // PhP5 only
}
Return true;
}
}
?>

Obviously, this is very helpful for us to control the data for accessing objects. If a programmer has directly accessed the username information, the above Code changes will destroy his code. However, we can use the (class) access method, as noted in the code above, to add a verification function without changing anything else. Note that the verification of username (in this example, the code cannot exceed 12 bytes) is independent of the setusername () method. The process from verification to storage to database is easy. In addition, this is a very good experience-based method. The less a method or class needs to be done, the more chance it will be used repeatedly. This is more obvious when you start to write a subclass. If you need a subclass and want to skip (ignore) some special details in the parent class method (behavior, if (for this details) the method is small and fine, (for modifying it) is just an instant process, and if this method is very bloated, for a variety of purposes, you may end up with a lot of code in the replication subclass.

For example, admin is a subclass of the user class. We may have different and more demanding password verification methods for adamin users. It is best to overwrite the verification method of the parent class and the entire setusername () method (in the subclass ).

More about accessors)
The following are some other examples to illustrate how to make the accessors more effective. In many cases, we may need to calculate the result rather than simply returning static data in the array. Another useful thing the access method can do is to update the value in the cache. When all changes (all operations on data) are performed using the setx () method, this is the time when we reset the value in the cache based on X.

So our class hierarchy becomes clearer:

The internal variable $ _ data is replaced with the protected private method (private methods) _ getdata () and _ setdata ()
This type of method is transferred to the abstract super class called record. Of course, it is a subclass of the user class.
This record class holds all the details of accessing the array $ _ data, calls the verification method before the content is modified, and sends the change notification to the records ), it is like sending an Object Storage Service (ObjectStore) instance to the center.

<? PHP
Class user extends record {

// --- Omitted code ---//

/**
* Do not show the actual password for the user, only some asterixes with the same strlen as the password value.
*/
Function password (){
$ Passlength = strlen ($ this-> _ getdata ('Password '));
Return str_repeat ('*', $ passlength );
}
/**
* Setting the user password is not affected.
*/
Function setpassword ($ newpassword ){
$ This-> _ setdata ('Password', $ newpassword );
}

/**
* Fullname is a derived attribute from firstname and lastname
* And does not need to be stored as a variable.
* It is therefore read-only, and has no 'setfullname () 'accessor method.
*/
Function fullname (){
Return $ this-> firstname (). "". $ this-> lastname ();
}

/**
* Spending limit returns the currency value of the user's spending limit.
* This value is stored as an int in the database, eliminating the need
* For more expensive decimal or double column types.
*/
Function spendinglimit (){
Return $ this-> _ getdata ('spendinglimit ')/100;
}

/**
* The set accessor multiplies the currency value by 100, so it can be stored in the database again
* As an int value.
*/
Function setspendinglimit ($ newspendlimit ){
$ This-> _ setdata ('spendinglimit ', $ newspendlimit * 100 );
}

/**
* The validatespendinglimit is not called in this class, but is called automatically by the _ setdata () method
* In the record superclass, which in turn is called by the setspendinglimit () method.
*/
Function validatespendinglimit (& $ somelimit ){
If (is_numeric ($ somelimit) and $ somelimit> = 0 ){
Return true;
} Else {
Throw new exception ("spending limit must be a non-negative integer"); // PhP5 only
}
}
}

/**
* Record is the superclass for All database objects.
*/
Abstract class record {
VaR $ _ DATA = array ();
VaR $ _ modifiedkeys = array (); // keeps track of which fields have changed since record was created/fetched

/**
* Returns an element from the $ _ DATA associative array.
*/
Function _ getdata ($ attributename ){
Return $ this-> _ DATA [$ attributename];
}

/**
* If the supplied value passes validation, this
* Sets the value in the $ _ DATA associative array.
*/
Function _ setdata ($ attributename, $ value ){
If ($ this-> validateattribute ($ attributename, $ value )){
If ($ value! = $ This-> _ DATA [$ attributename]) {
$ This-> _ DATA [$ attributename] = $ value;
$ This-> _ modifiedkeys [] = $ attributename;
$ This-> didchange ();
} Else {
// The new value is identical to the current one
// No change necessary
}
}
}

/**
* For an attribute named "foo", this looks for a method named "validatefoo ()"
* And callit if it exists. Otherwise this returns true (meaning validation passed ).
*/
Function validateattribute ($ attributename, & $ value ){
$ Methodname = 'validate'. $ attributename;
If (method_exists ($ this, $ methodname )){
Return $ this-> $ methodname ($ value );
} Else {
Return true;
}
}

Function didchange (){
// Configure y the ObjectStore that this record changed
}
}
?>

Now we have an abstract super class (record). We can transfer a large amount of code from the user class, let the sub-class of the user focus on the special projects of the user, such as the access and verification methods. You may have noticed that there is no SQL code in our record class. This is not an oversight or omission! The Object Storage Class (hidden in the second part) will be responsible for all interactions with the database, as well as the instantiation of our super class record. This makes our record class thinner and more efficient, which is an important factor in evaluating the efficiency of processing a large number of objects.

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.