Benefits of using objects in the database

Source: Internet
Author: User
Tags abstract array empty sql php code strlen variable
Objects | data | Database We all know how to get the rows (records) We need from MySQL, read the data, and then access some of the changes. Obviously it's also straightforward, and there's nothing to beat around this process. However, when we use object-oriented programming (OOP) to manage the data in our database, the process needs to be greatly improved. This article will make a simple description of how to design an object-facing way to manage the records of a database. All of the internal logic of your data will be encapsulated into a very structured record object that can provide a dedicated (single-minded) 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 (facing the Object Management database) more appealing.


Here's a list of the benefits of using objects to describe your database:


The access method (accessor methods) will allow you to fully control the read and write process of the attribute
Each level of records and attributes (operations) has a confirmation process
Getting objects intelligently from a relational table
The repetitive logical approach means that all data interactions have to go 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, rather than the cumbersome library (Lib) file.
There will be less chance of error when writing code and SQL query statements manually


Access method (accessor methods)

The access method is to assign a value to a variable of a class to an instance (instance). One example, I have a class called User, and there is an instance of $username, I'll write this accessor method (function), User->username () and User->setusername () to return and assign values to the instance.



<?php
Class User {
var $username;

function username () {
return $this->username;
}

function Setusername ($newUsername) {
$this->username = $newUsername;
}
}
?>




Here's a good reason for us to write this "special code". It will make it more flexible for developers to change the tedious work of classes, because this process will not require other PHP code that uses the class. Let's take a look at this more complete and trustworthy user class below.


The variable $username will no longer exist, and everything is integrated into the array $_data.
If the username is empty, the username () function will provide a default (default) value to it
The Setusername () procedure confirms that the username is in a standard format (such as word length, etc.) before accepting the value.

<?php
Class User {
var $_data = array (); Associative array containing all of 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 helps us to control the access to the object's data. If a programmer has directly accessed username information, the changes in the above code will destroy his code. However, we can use (class) Access methods, as commented in the above code, to add a validation function without changing anything else. Note that username validation (in the case of no more than 12 bytes) code is independent of the Setusername () method. The process from validating to storing to a database is easy. Moreover, this is a very good empirical method, the less a method or a class needs to be done, the greater the chance that it will be reused. This is even more apparent when you start to write a subclass, if you need a subclass, and also skip (ignore) some special details in the parent method (behavior), if the method (for this detail) is small and fine, (modifying it) is just an instant process, and if the method is very bloated, for a variety of purposes, You'll probably end up with a lot of code in the 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 show how to make the accessor more effective. Many times we might want to compute the result rather than simply return the static data in the array. One useful thing the access method can do is to update the values in the cache (updating). When all changes (all operations on the data) are passed through the Setx () method, this is the moment when we reset the values in the cache according to X.

So our level of class becomes clearer:

The processing of the internal variable $_data is replaced with the protected private method (private methods) _getdata () and _setdata ()
Such a method is shifted to the abstract superclass (super Class) called a record (records), which is, of course, a subclass of the user class
This class of records (record Class) grasps the details of all Access array $_data, invokes the validation method before the content is modified, and sends the notification of the change to the record (Records) as if it were sent to a central object store (ObjectStore) instance.

<?php
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 attributes 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 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-m, so it can is 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 are called automatically by the _setdata ()
* 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
}
}
}

/**
* 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 the attribute named "foo", this is 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 move a lot of code out of the user class and let the user's subclasses focus on the user's special items such as access and authentication methods. You may have noticed that there is no SQL code in our 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 smaller and more efficient, which is an important factor in evaluating our efficiency in dealing with a large number of objects.

If you are interested in reading this article based on the complete code (does not appear in the text of all the syntax errors), you can send me a letter to the mailbox sam@360works.com

Original address: http://www.phpbuilder.com/columns/barnum20030509.php3?page=1



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.