PHP數據庫操作面向對象的優點 - 中國WEB開發者網絡 (http://www.webasp.net) -- 技術教程 (http://www.webasp.net/article/) --- PHP數據庫操作面向對象的優點 (http://www.webasp.net/article/15/14705.htm) |
| -- 作者:未知 -- 發佈日期: 2004-11-09 |
| 我們都知道如何從Mysql獲取我們需要的行(記錄),讀取數據,然後存取一些改動。很明顯也很直接,在這個過程背後也沒有什麼拐彎抹角的。然而對於我們使用面對對象的程序設計(OOP)來管理我們數據庫中的數據時,這個過程就需要大大改進一下了。這篇文章將對如何設計一個面對對象的方式來管理數據庫的記錄做一個簡單的描述。你的數據當中的所有內部邏輯關係將被封裝到一個非常條理的記錄對象,這個對象能夠提供專門(專一)的確認代碼系統,轉化以及數據處理。隨著Zend Engine2 和PHP5的發佈,PHP開發者將會擁有更強大的面對對象的工具來輔助工作,這將使這個過程(面對對像地管理數據庫)更有吸引力。
以下列出了一些使用對像來描敘你的數據庫的有利方面: 存取方法(Accessor methods)將會使你對屬性的讀取和寫入過程做到完全的控制 每一級的每個記錄和屬性(的操作)都有確認過程 從關係表中智能的獲取對像 重複使用的邏輯方法意味著所有的數據交互都要通過相同的基礎代碼(codebase),這將使維護變得更加簡單 代碼簡單,因為不同的記錄的內部邏輯都已經包含在各自所處的類(class)當中,而不是繁瑣的庫(lib)文件 在手工編寫代碼和SQL查詢語句時,出錯的機會將更少 存取方法(Accessor methods) 存取方式是通過類給實例(instance)的變量賦值。一個例子,我有一個叫User的類,並且有一個實例$username,我會寫這樣的存取方法(函數),User->username()和User->setUsername()用來返回和給實例賦值。 <?php class User { var $username; function username() { return $this->username; } function setUsername($newUsername) { $this->username = $newUsername; } } ?> 這裡有很好的理由讓我們編寫這樣的「特別的代碼」。它將使開發者更靈活的改變類的繁瑣的工作,因為這一過程將不需要其他的使用類的php代碼。讓我們來看看下面這個更加完善的可信賴的User類。 變量$username將不復存在,所有的東西都被整合的放在數組$_data當中 如果username是空的話,username()函數將提供一個缺省(默認)的值給它 setUsername()過程將在接受值之前確認username是否合乎標準格式(如字長等) <?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; } } ?> 顯而易見,這對我們控制存取對象的數據有很大幫助。如果一個程序員已經直接地存取username的信息,以上代碼的變化將會破壞他的代碼。然而我們可以使用(類的)存取方法,就像上面代碼中註釋的那樣,添加一個驗證的功能而不需要改變任何其他的東西。注意username的驗證(例子當中是不能超過12字節)代碼是獨立在setUsername()方法之外的。從驗證到存儲到數據庫的過程輕而易舉。而且,這是個非常好的單憑經驗的方法,一個方法或一個類需要做的越少,它的重複使用的機會將會越大。這在你開始寫一個子類時更加明顯,假如你需要一個子類,並且又要跳過(忽略)父類方法(行為)中的一些特殊的細節,如果(針對這個細節的)方法很小而又精細,(修改它)只是一瞬間的過程,而如果這個方法非常臃腫,針對多種目的,你可能將在複製子類中大量代碼中鬱悶而終。 比方說,假如Admin是User類的一個子類。我們對adamin的用戶可能會有不同的,相對苛刻一些的密碼驗證方法。最好是跨過父類的驗證方法和整個setUsername()方法(在子類中重寫)。 更多關於存取器(Accessor) 下面是一些其他的例子來說明如何使存取器用的更有效果。很多時候我們可能要計算結果,而不是簡單的返回數組中的靜態數據。存取方法還能做的一個有用的事情就是更新(updating)緩存中的值。當所有的變動(對數據的所有操作)都要通過setX()方法的時候,這正是我們根據X來重置緩存中的值的時刻。 於是我們的這個類層次變得更加明瞭: 內部變量$_data的處理被替換成受保護的私有方法(private methods)_getData()和_setData() 這類方法被轉移到被稱作記錄(Record)的抽像的超級類(super class),當然它是User類下的子類 這個記錄類(Record class)掌握所有存取數組$_data的細節,在內容被修改之前調用驗證的方法,以及將變更的通知發給記錄(Records),就像發給中心對像存儲(ObjectStore)實例。 <?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 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 } } ?> 現在我們擁有了一個抽像的超級類(Record),我們可以將User類裡面大量的代碼轉移出來,而讓這個User的子類來關注User的特殊項目如存取和驗證方法。你可能已經注意到在我們的這個紀錄類(Record class)沒有任何的SQL代碼。這並不是疏忽或者遺漏!對像存儲類(ObjectStore class)(隱藏在第二部分)將負責所有和數據庫的交互,還有我們的超級類Record的實例化。這樣使我們的Record類更加瘦小而又有效率,而這對於評價我們處理大量對象的效率的時候是個重要因素。 |
| webasp.net |