首頁  >  文章  >  後端開發  >  昆汀·澤瓦斯的 DBO

昆汀·澤瓦斯的 DBO

WBOY
WBOY原創
2016-07-25 09:10:09816瀏覽
《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