国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial PHP數(shù)據(jù)庫操作面向?qū)ο蟮膬?yōu)點_PHP

PHP數(shù)據(jù)庫操作面向?qū)ο蟮膬?yōu)點_PHP

Jun 01, 2016 pm 12:41 PM
the advantage object us operate database method For

我們都知道如何從Mysql獲取我們需要的行(記錄),讀取數(shù)據(jù),然后存取一些改動。很明顯也很直接,在這個過程背后也沒有什么拐彎抹角的。然而對于我們使用面對對象的程序設(shè)計(OOP)來管理我們數(shù)據(jù)庫中的數(shù)據(jù)時,這個過程就需要大大改進一下了。這篇文章將對如何設(shè)計一個面對對象的方式來管理數(shù)據(jù)庫的記錄做一個簡單的描述。你的數(shù)據(jù)當(dāng)中的所有內(nèi)部邏輯關(guān)系將被封裝到一個非常條理的記錄對象,這個對象能夠提供專門(專一)的確認(rèn)代碼系統(tǒng),轉(zhuǎn)化以及數(shù)據(jù)處理。隨著Zend Engine2 和PHP5的發(fā)布,PHP開發(fā)者將會擁有更強大的面對對象的工具來輔助工作,這將使這個過程(面對對象地管理數(shù)據(jù)庫)更有吸引力。


以下列出了一些使用對象來描敘你的數(shù)據(jù)庫的有利方面:


存取方法(Accessor methods)將會使你對屬性的讀取和寫入過程做到完全的控制
每一級的每個記錄和屬性(的操作)都有確認(rèn)過程
從關(guān)系表中智能的獲取對象
重復(fù)使用的邏輯方法意味著所有的數(shù)據(jù)交互都要通過相同的基礎(chǔ)代碼(codebase),這將使維護變得更加簡單
代碼簡單,因為不同的記錄的內(nèi)部邏輯都已經(jīng)包含在各自所處的類(class)當(dāng)中,而不是繁瑣的庫(lib)文件
在手工編寫代碼和SQL查詢語句時,出錯的機會將更少


存取方法(Accessor methods)

存取方式是通過類給實例(instance)的變量賦值。一個例子,我有一個叫User的類,并且有一個實例$username,我會寫這樣的存取方法(函數(shù)),User->username()和User->setUsername()用來返回和給實例賦值。



class User {
var $username;

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

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




這里有很好的理由讓我們編寫這樣的“特別的代碼”。它將使開發(fā)者更靈活的改變類的繁瑣的工作,因為這一過程將不需要其他的使用類的php代碼。讓我們來看看下面這個更加完善的可信賴的User類。


變量$username將不復(fù)存在,所有的東西都被整合的放在數(shù)組$_data當(dāng)中
如果username是空的話,username()函數(shù)將提供一個缺?。J(rèn))的值給它
setUsername()過程將在接受值之前確認(rèn)username是否合乎標(biāo)準(zhǔn)格式(如字長等)

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;
}
}
?>



顯而易見,這對我們控制存取對象的數(shù)據(jù)有很大幫助。如果一個程序員已經(jīng)直接地存取username的信息,以上代碼的變化將會破壞他的代碼。然而我們可以使用(類的)存取方法,就像上面代碼中注釋的那樣,添加一個驗證的功能而不需要改變?nèi)魏纹渌臇|西。注意username的驗證(例子當(dāng)中是不能超過12字節(jié))代碼是獨立在setUsername()方法之外的。從驗證到存儲到數(shù)據(jù)庫的過程輕而易舉。而且,這是個非常好的單憑經(jīng)驗的方法,一個方法或一個類需要做的越少,它的重復(fù)使用的機會將會越大。這在你開始寫一個子類時更加明顯,假如你需要一個子類,并且又要跳過(忽略)父類方法(行為)中的一些特殊的細節(jié),如果(針對這個細節(jié)的)方法很小而又精細,(修改它)只是一瞬間的過程,而如果這個方法非常臃腫,針對多種目的,你可能將在復(fù)制子類中大量代碼中郁悶而終。

比方說,假如Admin是User類的一個子類。我們對adamin的用戶可能會有不同的,相對苛刻一些的密碼驗證方法。最好是跨過父類的驗證方法和整個setUsername()方法(在子類中重寫)。

更多關(guān)于存取器(Accessor)
下面是一些其他的例子來說明如何使存取器用的更有效果。很多時候我們可能要計算結(jié)果,而不是簡單的返回數(shù)組中的靜態(tài)數(shù)據(jù)。存取方法還能做的一個有用的事情就是更新(updating)緩存中的值。當(dāng)所有的變動(對數(shù)據(jù)的所有操作)都要通過setX()方法的時候,這正是我們根據(jù)X來重置緩存中的值的時刻。

于是我們的這個類層次變得更加明了:

內(nèi)部變量$_data的處理被替換成受保護的私有方法(private methods)_getData()和_setData()
這類方法被轉(zhuǎn)移到被稱作記錄(Record)的抽象的超級類(super class),當(dāng)然它是User類下的子類
這個記錄類(Record class)掌握所有存取數(shù)組$_data的細節(jié),在內(nèi)容被修改之前調(diào)用驗證的方法,以及將變更的通知發(fā)給記錄(Records),就像發(fā)給中心對象存儲(ObjectStore)實例。

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 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
}
}
?>



現(xiàn)在我們擁有了一個抽象的超級類(Record),我們可以將User類里面大量的代碼轉(zhuǎn)移出來,而讓這個User的子類來關(guān)注User的特殊項目如存取和驗證方法。你可能已經(jīng)注意到在我們的這個紀(jì)錄類(Record class)沒有任何的SQL代碼。這并不是疏忽或者遺漏!對象存儲類(ObjectStore class)(隱藏在第二部分)將負(fù)責(zé)所有和數(shù)據(jù)庫的交互,還有我們的超級類Record的實例化。這樣使我們的Record類更加瘦小而又有效率,而這對于評價我們處理大量對象的效率的時候是個重要因素。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

Oracle's Role in the Business World Oracle's Role in the Business World Apr 23, 2025 am 12:01 AM

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL vs. Other Databases: Comparing the Options MySQL vs. Other Databases: Comparing the Options Apr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

MySQL: A Beginner-Friendly Approach to Data Storage MySQL: A Beginner-Friendly Approach to Data Storage Apr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

See all articles