首頁 後端開發 php教程 昆汀·澤瓦斯的 DBO

昆汀·澤瓦斯的 DBO

Jul 25, 2016 am 09:10 AM

《Web 2.0 開發實戰》一書的作者,Quentin Zervaas 在書中提到的一個簡易PHP資料存取物件。
  1. /**
  2. * DatabaseObject
  3. *
  4. * 用於輕鬆操作資料庫表中資料的抽象類別
  5. * 透過簡單的載入/儲存/刪除方法
  6. */
  7. 抽象類別 DatabaseObject
  8. {
  9. const TYPE_TIMESTAMP = 1;
  10. {
  11. const TYPE_TIMESTAMP = 1;
  12. conOOst 2;
  13. protected static $types = array(self::TYPE_TIMESTAMP, self::TYPE_BOOLEAN);
  14. private $_id = null;
  15. private $arra_perties;
  16. protected $_db = null;
  17. protected $_table = '';
  18. protected $_idField = '';
  19. public function __construct(Zend_b_AdAd表, $idField)
  20. {
  21. $this->_db = $db;
  22. $this->_table = $table;
  23. $this->_idField = $idField;
  24. }
  25. public function load($id, $field = null)
  26. {
  27. if (strlen($field) == 0)
  28. $field = $this->_idField ;
  29. if ($field == $this->_idField) {
  30. $id = (int) $id;
  31. if ($id 回傳false ;
  32. }
  33. $query = sprintf('從%s 中選擇%s,其中%s = ?',
  34. join(', ', $this->getSelectFields()),
  35. $this- >_table,
  36. $field);
  37. $query = $this->_db->quoteInto($query, $id);
  38. return $this->_load($query );
  39. }
  40. protected function getSelectFields($prefix = '')
  41. {
  42. $fields = array($prefix . $this->_idField);
  43. foreach ($prefix . $this->_idField);
  44. foreach ($prefix . $this->_idField);
  45. foreach ($prefix . $this->_idField);
  46. foreach ($prefix> foreach ($ this->_properties as $k => $v)
  47. $fields[] = $prefix 。 load ($query)
  48. {
  49. $result = $this->_db->query ($query);
  50. $row = $result->fetch();
  51. if (!$row )
  52. 回傳false;
  53. $this->_init($row );
  54. $this->postLoad();
  55. 回傳true;
  56. }
  57. public function _init($row)
  58. {
  59. foreach ($this->_properties as $k => $v) {
  60. $val = $row[$k];
  61. switch ($v['type']) {
  62. case self::TYPE_TIMESTAMP:
  63. if (!is_null($val))
  64. $val = strtotime($val);
  65. break;
  66. case self::TYPE_BOOLEAN:
  67. $val = (bool) $val;
  68. 規則;
  69. }
  70. $this->_properties[$k][$k][$k] ' value'] = $val;
  71. }
  72. $this ->_id = (int) $row[$this->_idField];
  73. }
  74. public function save ( $useTransactions = true)
  75. {
  76. $update = $this->isSaved();
  77. if ($useTransactions)
  78. $this->_db->beginTransaction();
  79. if ($update)
  80. $commit = $this->preUpdate();
  81. else
  82. $commit = $this->preInsert();
  83. if (> if (> if ( ! $commit) {
  84. if ( $useTransactions)
  85. $this->_db->rollback();
  86. return false;
  87. }
  88. $row = array();
  89. foreach ( $this->_properties 為 $k =>; $v) {
  90. if ($update && !$v['updated'])
  91. continue;
  92. switch ($v['type']) {
  93. case self:: TYPE_TIMESTAMP:
  94. if (!is_null($v['value'])) {
  95. if ($this->_db instanceof Zend_Db_Adapter_Pdo_Pgsql)
  96. $v['value'] = date'Y-m-m i:sO', $v['value']);
  97. else
  98. $v['value'] = date('Y-m-d H:i:s', $v['value']);
  99. }
  100. 中斷;
  101. case self::TYPE_BOOLEAN:
  102. $v['value'] = (int) ((bool) $v['value']);
  103. break;
  104. }
  105. $row[$k] = $v['value'];
  106. }
  107. if (count($row) > 0) {
  108. // 執行插入/更新
  109. if ($update) {
  110. $this->_db->update($this->_table, $row, sprintf('%s = %d) ', $ this->_idField, $this->getId()));
  111. }
  112. else {
  113. $this->_db->insert($this->_table, $row);
  114. $this->_id = $this->_db->lastInsertId ($this->_table , $this->_idField);
  115. }
  116. }
  117. // 更新內部id
  118. if ($commit) {
  119. if ($update)
  120. $commit = $this->postUpdate();
  121. else
  122. $commit = $this->postInsert();
  123. }
  124. if ($useTransactions) {
  125. if ( $commit)
  126. $this->_db->commit();
  127. else
  128. $this->_db->rollback();
  129. }
  130. return $commit;
  131. }
  132. public function delete($useTransactions = true)
  133. {
  134. if (!$this->isSaved() )
  135. return false;
  136. if ( $useTransactions)
  137. $this->_db->beginTransaction();
  138. $commit = $this->preDelete( );
  139. if ($commit) {
  140. $ this->_db->delete($this->_table, sprintf('%s = %d', $this->; _idField, $this->getId()));
  141. }
  142. else {
  143. if ($useTransactions)
  144. $this->_db->rollback();
  145. return false;
  146. }
  147. $commit = $this->postDelete();
  148. $this->_id = null;
  149. if ($useTransactions) {
  150. if ($commit)
  151. $this->_db->commit();
  152. else
  153. $this->_db->rollback();
  154. }
  155. return $commit;
  156. }
  157. public function isSaved()
  158. {
  159. { return $this->getId() > 0;
  160. }
  161. public function getId()
  162. {
  163. return (int) $this->_id;
  164. }
  165. public function getDb()
  166. {
  167. return $this->_db;
  168. }
  169. public function __set($name, $value)
  170. {
  171. if (array_key_exists($name, $this->_properties)) {
  172. $this->_properties[$name]['value'] = $value;
  173. $this->_properties[$name][' 。 array_key_exists($name, $this->_properties) ? $this->_properties[$name]['value'] : null;
  174. }
  175. protected function add($field, $default = null, $type = null)
  176. {
  177. $this->_properties[$field] = array('value' => $default,
  178. 'type' => in_array($type, self::$types) ? $type : null,
  179. ' Updated' => false);
  180. }
  181. 受保護函數preInsert()
  182. {
  183. 回傳true;
  184. }
  185. 受保護函數postInsert ()
  186. {
  187. 回傳true;
  188. }
  189. 受保護函數preUpdate()
  190. {
  191. 回傳true;
  192. }
  193. 受保護函數postUp )
  194. {
  195. 回傳true;
  196. }
  197. 受保護函數preDelete()
  198. {
  199. 回傳true;
  200. }
  201. 受保護函數postDelete ()
  202. {
  203. return true;
  204. }
  205. protected function postLoad()
  206. {
  207. return true;
  208. }
  209. }
  210. return true;
  211. }
  212. 函數BuildMultiple($db, $class, $data)
  213. {
  214. $ret = array();
  215. if (!class_exists($class))
  216. throw new Exception('未未定義的類別指定的: ' 。 '類別不是來自DatabaseObject 擴充的' );
  217. foreach ($data as $row) {
  218. $obj = new $class($db);
  219. $obj->_init($row );
  220. $ret[$obj->getId()] = $obj;
  221. }
  222. return $ret;
  223. }
  224. }
  225. 複製程式碼
    1. class DatabaseObject_User extends DatabaseObject
    2. {
    3. static $userTypes = array('member' => 'Member',
    4. '管理員> ' => '管理員');
    5. public $profile = null;
    6. public $_newPassword = null;
    7. public function __construct($db)
    8. {
    9. Parent::__construct($db, 'users', 'user_id');
    10. $this->add('使用者名稱');
    11. $this->add('密碼') ;
    12. $this->add('user_type', 'member');
    13. $this->add('ts_created', time(), self::TYPE_TIMESTAMP);
    14. $this->add(' ts_last_login', null, self::TYPE_TIMESTAMP);
    15. $this->profile = new Profile_User($db);
    16. }
    17. protected function presert( ) $this->_newPassword = Text_Password::create(8);
    18. $this->password = $this->_newPassword;
    19. return true;
    20. }
    21. protected function postLoted function postLoted function postLoted function postLoted function postLoted function postLoted function postLoted function postLoted function postLoted function postLoted function postLoted function postLoted function postLoted function postLoted function postLoted function postLoted function post」 ()
    22. {
    23. $this->profile->setUserId($this->getId());
    24. $this->profile-> ;load();
    25. }
    26. $this->profile->setUserId($this->getId());
    27. $this->profile->save(false);
    28. $this->sendEmail('user-register.tpl');
    29. return true;
    30. }
    31. 受保護函數postUpdate()
    32. {
    33. $this $this ->profile->save(false);
    34. return true;
    35. }
    36. 受保護函數preDelete()
    37. {
    38. $this->profile->delete();
    39. return true;
    40. }
    41. public function sendEmail($tpl)
    42. {
    43. $templater = new Templater();
    44. $templater-> $templater = new Templater();
    45. $templater->user =thislater->user =this;
    46. // 取得電子郵件正文
    47. $body = $templater->render('email /'. $tpl);
    48. // 從第一行擷取主題
    49. list($subject, $body) = preg_split('/r|n/', $body, 2);
    50. // 現在設定並傳送電子郵件
    51. $mail = new Zend_Mail();
    52. // 在「食譜」中設定食譜位址與使用者全名
    53. $mail->addTo($this->個人資料->電子郵件,
    54. trim( $this->個人資料->first_name 。 ' ' .
    55. $this->個人資料->; last_name));
    56. // 從設定中取得管理員「寄件者」詳細資料
    57. $mail->setFrom(Zend_Registry::get('config')->email->from- >email,
    58. Zend_Registry::get('config')->email->from->name);
    59. // 設定主題和正文並發送郵件
    60. $mail->setSubject( trim($subject));
    61. $mail->setBodyText(trim($body));
    62. $mail->send();
    63. }
    64. public function createAuthIdentity()
    65. public function createAuthIdentity()
    66. {
    67. $identity = new stdClass;
    68. $identity->user_id = $this->getId();
    69. $identity->username = $this->使用者名稱;
    70. $identity ->user_type = $this->user_type;
    71. $identity->first_name = $this->profile->first_name;
    72. $identity ->last_name = $this->profile->last_name;
    73. $>身分->電子郵件= $this->個人資料->電子郵件;
    74. return $identity;
    75. }
    76. public function loginSuccess()
    77. {
    78. $ this-> ts_last_login = time();
    79. unset($this->profile->new_password);
    80. 取消設定($這->個人資料->new_password_ts);
    81. 取消設定($這- >個人資料->new_password_key);
    82. $這->save();
    83. $ message = sprintf('%s 用戶%s 成功登入嘗試',
    84. $_SERVER['REMOTE_ADDR' ],
    85. $this->使用者名稱);
    86. $logger = Zend_Registry:: get('logger');
    87. $logger->notice($message);
    88. }
    89. static public function LoginFailure($username, $code = '')
    90. {
    91. switch ($code) {
    92. case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FO:break;
    93. case Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS:
    94. $reason = '使用此使用者名稱找到多個使用者';
    95. break;
    96. casePend_Auth_Result; reason = '密碼無效';
    97. break;
    98. 預設值:
    99. $reason = '';
    100. }
    101. $message = sprintf('%s 使用者%s 登入嘗試失敗',
    102. $_SERVER['REMOTE_ADDR'],
    103. $用戶名);
    104. if (strlen($reason) > 0)
    105. $message .= sprintf(' (% s)' , $reason);
    106. $logger = Zend_Registry::get('logger');
    107. $logger->warn($message);
    108. }
    109. 公用函數fetchPassword()
    110. {
    111. if (!$this->isSaved())
    112. return false;
    113. // 產生新密碼屬性
    114. $this->_newPassword = Text_Password::create(8);
    115. $this->profile->new_password = md5($this->_newPassword);
    116. $this->profile->new_password_ts = time();
    117. $this ->profile->new_password_key = md5(uniqid() .
    118. $this->getId() .
    119. $this->_newPassword);
    120. / / 將新密碼儲存到個人資料並寄電子郵件
    121. $this->profile->save();
    122. $this->sendEmail('user-fetch-password.tpl');
    123. return true;
    124. }
    125. public function recognizeNewPassword($key)
    126. {
    127. // 檢查是否設定了有效的密碼重設資料
    128. if (!isset($這->個人資料->新密碼)
    129. || !isset($this->個人資料->new_password_ts)
    130. || !isset($this->profile->new_password_key)) {
    131. return false;
    132. }
    133. // 檢查密碼是否在一天內確認
    134. if (time() - $this->profile->new_password_ts > 86400)
    135. return false;
    136. //檢查金鑰是否正確
    137. if ($this->; profile->new_password_key != $key)
    138. return false;
    139. // 一切都有效,現在更新帳戶以使用新密碼
    140. // 繞過本地設定器new_password 已經是md5
    141. 父級::__set('password', $this->profile->new_password);
    142. unset($this- >profile->new_password);
    143. unset($this->profile->new_password_ts);
    144. unset($this->profile->new_password_key);
    145. // 最後,儲存更新後的使用者記錄與更新的個人資料
    146. return $this->save();
    147. }
    148. public function usernameExists($username)
    149. {
    150. $query = sprintf(' select count(*)) as num from %s where username = ?',
    151. $this->_table);
    152. $result = $this->_db->fetchOne($query, $username );
    153. 回傳$結果> 0;
    154. }
    155. static public function IsValidUsername($username)
    156. {
    157. $validator = new Zend_Valusername)
    158. {
    159. $validator = new Zend_Validate_Alnum(); return $validator->isValid($username);
    160. }
    161. public function __set($name, $value)
    162. {
    163. switch ($name) {
    164. case 'password ':
    165. $value = md5($ value);
    166. break;
    167. case 'user_type':
    168. if (!array_key_exists($value, self::$userTypes))
    169. $value = 'member';
    170. Break;
    171. }
    172. return Parent::__set($name, $value);
    173. }
    174. }
    175. ?>
    複製程式碼

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

在PHP API中說明JSON Web令牌(JWT)及其用例。 在PHP API中說明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

會話如何劫持工作,如何在PHP中減輕它? 會話如何劫持工作,如何在PHP中減輕它? Apr 06, 2025 am 12:02 AM

會話劫持可以通過以下步驟實現:1.獲取會話ID,2.使用會話ID,3.保持會話活躍。在PHP中防範會話劫持的方法包括:1.使用session_regenerate_id()函數重新生成會話ID,2.通過數據庫存儲會話數據,3.確保所有會話數據通過HTTPS傳輸。

PHP 8.1中的枚舉(枚舉)是什麼? PHP 8.1中的枚舉(枚舉)是什麼? Apr 03, 2025 am 12:05 AM

PHP8.1中的枚舉功能通過定義命名常量增強了代碼的清晰度和類型安全性。 1)枚舉可以是整數、字符串或對象,提高了代碼可讀性和類型安全性。 2)枚舉基於類,支持面向對象特性,如遍歷和反射。 3)枚舉可用於比較和賦值,確保類型安全。 4)枚舉支持添加方法,實現複雜邏輯。 5)嚴格類型檢查和錯誤處理可避免常見錯誤。 6)枚舉減少魔法值,提升可維護性,但需注意性能優化。

描述紮實的原則及其如何應用於PHP的開發。 描述紮實的原則及其如何應用於PHP的開發。 Apr 03, 2025 am 12:04 AM

SOLID原則在PHP開發中的應用包括:1.單一職責原則(SRP):每個類只負責一個功能。 2.開閉原則(OCP):通過擴展而非修改實現變化。 3.里氏替換原則(LSP):子類可替換基類而不影響程序正確性。 4.接口隔離原則(ISP):使用細粒度接口避免依賴不使用的方法。 5.依賴倒置原則(DIP):高低層次模塊都依賴於抽象,通過依賴注入實現。

在PHPStorm中如何進行CLI模式的調試? 在PHPStorm中如何進行CLI模式的調試? Apr 01, 2025 pm 02:57 PM

在PHPStorm中如何進行CLI模式的調試?在使用PHPStorm進行開發時,有時我們需要在命令行界面(CLI)模式下調試PHP�...

如何用PHP的cURL庫發送包含JSON數據的POST請求? 如何用PHP的cURL庫發送包含JSON數據的POST請求? Apr 01, 2025 pm 03:12 PM

使用PHP的cURL庫發送JSON數據在PHP開發中,經常需要與外部API進行交互,其中一種常見的方式是使用cURL庫發送POST�...

如何在系統重啟後自動設置unixsocket的權限? 如何在系統重啟後自動設置unixsocket的權限? Mar 31, 2025 pm 11:54 PM

如何在系統重啟後自動設置unixsocket的權限每次系統重啟後,我們都需要執行以下命令來修改unixsocket的權限:sudo...

See all articles