We all know how to get the rows (records) We need from MySQL, read the data, and then access some changes. It's obvious and straightforward, and there's no roundabout way behind the process. However, when we use object-oriented programming (OOP) to manage the data in our database, this process needs to be greatly improved. This article will make a simple description of how to design an object-facing way to manage the database records. All the internal logic in your data will be encapsulated into a very organized record object that provides a dedicated (specific) validation code system, transformation, and data processing. With the release of Zend Engine2 and PHP5, PHP developers will have more powerful tools to support their work, which will make this process (managing the database in the face of objects) more appealing.
Here are some useful aspects of using objects to describe your database:
The Access Method (Accessor methods) will give you complete control over the read and write process of the property
Each level has a confirmation process for each record and attribute (the operation)
Getting objects intelligently from a relational table
The repeated use of logical methods means that all data interactions pass through the same underlying code (codebase), which makes maintenance easier
The code is simple because the internal logic of the different records is already contained within the class, not the cumbersome library (Lib) file
Fewer opportunities for errors when writing code and SQL query statements manually
Access method (Accessor methods)
Access is done by assigning a value to a variable in the class to the instance (instance). An example, I have a class called User, and there is an instance of $username, I will write such access methods (functions), User->username () and User->setusername () to return and assign values to the instance.
Class User {
var $username;
function username () {
return $this->username;
}
function Setusername ($newUsername) {
$this->username = $newUsername;
}
}
?>
There are good reasons for us to write this "special code". It will give developers more flexibility in changing the tedious work of the class, because this process will not require other PHP code to use the class. Let's take a look at the more complete and trustworthy user class below.
Variable $username will no longer exist, everything is integrated into the array $_data
If username is empty, the username () function will provide a default (default) value to it
The Setusername () process will confirm that the username conforms to the standard format (such as word length) before accepting the value.
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 of the Access object. If a programmer has access to username information directly, the changes in the above code will break his code. However, we can use the (class) access method, just as commented in the code above, to add a validation function without changing anything else. Note that the validation of username (in the example, not more than 12 bytes) is independent of the Setusername () method. The process from validation to storage to the database is a breeze. Moreover, this is a very good experience-based approach, the less a method or a class needs to be done, the greater the chance of its reuse. This is even more noticeable when you start to write a subclass, and if you need a subclass, and you skip (ignore) Some of the special details of the parent's method (behavior), if the method (for that detail) is small and fine, it's just a momentary process, and if the method is bloated, for multiple purposes, You might end up in a lot of code in a copy subclass.
For example, if admin is a subclass of the user class. We may have different, relatively harsh password authentication methods for adamin users. It is best to cross the validation method of the parent class and the entire Setusername () method (overridden in a subclass).
More about accessors (Accessor)
Here are some other examples to illustrate how to make the accessors more effective. Many times we may want to calculate the result rather than simply returning the static data in the array. A useful thing to do with the access method is to update the values in the cache (updating). When all the changes (all operations to the data) are going through the Setx () method, this is exactly the moment we reset the values in the cache based on X.
So our class level becomes clearer:
The processing of the internal variable $_data is replaced with a protected private method (private methods) _getdata () and _setdata ()
This type of method is transferred to the abstract super class called the record (the "Super Class"), which is, of course, a subclass of the user class.
The record class holds the details of all Access array $_data, invokes the method of validation before the content is modified, and sends notification of changes to the record (Records), as if it were sent to the Central object Store (ObjectStore) instance.
Class User extends Record {
---omitted CODE---//
/**
* Don't 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 have 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 a 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 and so it can be stored in the database again
* As an INT value.
*/
function Setspendinglimit ($newSpendLimit) {
$this->_setdata (' Spendinglimit ', $newSpendLimit * 100);
}
/**
* The Validatespendinglimit is isn't called in this class, but is called automatically by the _setdata () method
* In the Record superclass, which in turn are 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 has 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
No change necessary
}
}
}
/**
* For the attribute named "foo", this looks for a method named "Validatefoo ()"
* and calls it 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 () {
Notify the objectstore that this record changed
}
}
?>
Now that we have an abstract super Class (Record), we can transfer a lot of code inside the user class and let the user's subclass focus on the user's special projects such as access and validation methods. You may have noticed that there is no SQL code in our record class (record Class). This is not negligence or omission! The object storage class (ObjectStore 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 leaner and more efficient, which is an important factor in evaluating our efficiency in dealing with a large number of objects.
http://www.bkjia.com/PHPjc/313989.html www.bkjia.com true http://www.bkjia.com/PHPjc/313989.html techarticle we all know how to get the rows (records) We need from MySQL, read the data, and then access some changes. Obviously also very direct, behind this process there is no roundabout ...