Quentin Zervaas's DBO

Source: Internet
Author: User
Quentin Zervaas, author of the book "Web 2.0 Development," is a simple PHP data Access object mentioned in the book.
  1. /**
  2. * Databaseobject
  3. *
  4. * Abstract class used to easily manipulate data in a database table
  5. * Via Simple Load/save/delete methods
  6. */
  7. Abstract class Databaseobject
  8. {
  9. Const TYPE_TIMESTAMP = 1;
  10. Const Type_boolean = 2;
  11. protected static $types = Array (Self::type_timestamp, Self::type_boolean);
  12. Private $_id = null;
  13. Private $_properties = Array ();
  14. protected $_db = null;
  15. protected $_table = ";
  16. protected $_idfield = ";
  17. Public function __construct (zend_db_adapter_abstract $db, $table, $idField)
  18. {
  19. $this->_db = $db;
  20. $this->_table = $table;
  21. $this->_idfield = $idField;
  22. }
  23. Public function Load ($id, $field = null)
  24. {
  25. if (strlen ($field) = = 0)
  26. $field = $this->_idfield;
  27. if ($field = = $this->_idfield) {
  28. $id = (int) $id;
  29. if ($id <= 0)
  30. return false;
  31. }
  32. $query = sprintf (' Select%s from%s where%s =? ',
  33. Join (', ', $this->getselectfields ()),
  34. $this->_table,
  35. $field);
  36. $query = $this->_db->quoteinto ($query, $id);
  37. return $this->_load ($query);
  38. }
  39. protected function Getselectfields ($prefix = ")
  40. {
  41. $fields = Array ($prefix. $this->_idfield);
  42. foreach ($this->_properties as $k = $v)
  43. $fields [] = $prefix. $k;
  44. return $fields;
  45. }
  46. protected function _load ($query)
  47. {
  48. $result = $this->_db->query ($query);
  49. $row = $result->fetch ();
  50. if (! $row)
  51. return false;
  52. $this->_init ($row);
  53. $this->postload ();
  54. return true;
  55. }
  56. Public Function _init ($row)
  57. {
  58. foreach ($this->_properties as $k = + $v) {
  59. $val = $row [$k];
  60. Switch ($v [' type ']) {
  61. Case Self::type_timestamp:
  62. if (!is_null ($val))
  63. $val = Strtotime ($val);
  64. Break
  65. Case Self::type_boolean:
  66. $val = (bool) $val;
  67. Break
  68. }
  69. $this->_properties[$k [' value '] = $val;
  70. }
  71. $this->_id = (int) $row [$this->_idfield];
  72. }
  73. Public Function Save ($useTransactions = True)
  74. {
  75. $update = $this->issaved ();
  76. if ($useTransactions)
  77. $this->_db->begintransaction ();
  78. if ($update)
  79. $commit = $this->preupdate ();
  80. Else
  81. $commit = $this->preinsert ();
  82. if (! $commit) {
  83. if ($useTransactions)
  84. $this->_db->rollback ();
  85. return false;
  86. }
  87. $row = Array ();
  88. foreach ($this->_properties as $k = + $v) {
  89. if ($update &&! $v [' Updated '])
  90. Continue
  91. Switch ($v [' type ']) {
  92. Case Self::type_timestamp:
  93. if (!is_null ($v [' value ')]) {
  94. if ($this->_db instanceof Zend_db_adapter_pdo_pgsql)
  95. $v [' value '] = Date (' y-m-d h:i:so ', $v [' value ']);
  96. Else
  97. $v [' value '] = Date (' y-m-d h:i:s ', $v [' value ']);
  98. }
  99. Break
  100. Case Self::type_boolean:
  101. $v [' value '] = (int) ((bool) $v [' value ']);
  102. Break
  103. }
  104. $row [$k] = $v [' value '];
  105. }
  106. if (count ($row) > 0) {
  107. Perform insert/update
  108. if ($update) {
  109. $this->_db->update ($this->_table, $row, sprintf ('%s =%d ', $this->_idfield, $this->getid ()));
  110. }
  111. else {
  112. $this->_db->insert ($this->_table, $row);
  113. $this->_id = $this->_db->lastinsertid ($this->_table, $this->_idfield);
  114. }
  115. }
  116. Update Internal ID
  117. if ($commit) {
  118. if ($update)
  119. $commit = $this->postupdate ();
  120. Else
  121. $commit = $this->postinsert ();
  122. }
  123. if ($useTransactions) {
  124. if ($commit)
  125. $this->_db->commit ();
  126. Else
  127. $this->_db->rollback ();
  128. }
  129. return $commit;
  130. }
  131. Public Function Delete ($useTransactions = True)
  132. {
  133. if (! $this->issaved ())
  134. return false;
  135. if ($useTransactions)
  136. $this->_db->begintransaction ();
  137. $commit = $this->predelete ();
  138. if ($commit) {
  139. $this->_db->delete ($this->_table, sprintf ('%s =%d ', $this->_idfield, $this->getid ()));
  140. }
  141. else {
  142. if ($useTransactions)
  143. $this->_db->rollback ();
  144. return false;
  145. }
  146. $commit = $this->postdelete ();
  147. $this->_id = null;
  148. if ($useTransactions) {
  149. if ($commit)
  150. $this->_db->commit ();
  151. Else
  152. $this->_db->rollback ();
  153. }
  154. return $commit;
  155. }
  156. Public Function issaved ()
  157. {
  158. return $this->getid () > 0;
  159. }
  160. Public Function GetId ()
  161. {
  162. return (int) $this->_id;
  163. }
  164. Public Function Getdb ()
  165. {
  166. return $this->_db;
  167. }
  168. Public Function __set ($name, $value)
  169. {
  170. if (Array_key_exists ($name, $this->_properties)) {
  171. $this->_properties[$name [' value '] = $value;
  172. $this->_properties[$name [' updated '] = true;
  173. return true;
  174. }
  175. return false;
  176. }
  177. Public Function __get ($name)
  178. {
  179. Return array_key_exists ($name, $this->_properties)? $this->_properties[$name [' value ']: null;
  180. }
  181. protected function Add ($field, $default = null, $type = NULL)
  182. {
  183. $this->_properties[$field] = Array (' value ' = = $default,
  184. ' Type ' = In_array ($type, Self:: $types)? $type: null,
  185. ' Updated ' = false);
  186. }
  187. protected function Preinsert ()
  188. {
  189. return true;
  190. }
  191. protected function Postinsert ()
  192. {
  193. return true;
  194. }
  195. protected function Preupdate ()
  196. {
  197. return true;
  198. }
  199. protected function Postupdate ()
  200. {
  201. return true;
  202. }
  203. protected function Predelete ()
  204. {
  205. return true;
  206. }
  207. protected function Postdelete ()
  208. {
  209. return true;
  210. }
  211. protected function Postload ()
  212. {
  213. return true;
  214. }
  215. public static function Buildmultiple ($db, $class, $data)
  216. {
  217. $ret = Array ();
  218. if (!class_exists ($class))
  219. throw new Exception (' Undefined class specified: '. $class);
  220. $TESTOBJ = new $class ($DB);
  221. if (! $TESTOBJ instanceof Databaseobject)
  222. throw new Exception (' Class does not extend from databaseobject ');
  223. foreach ($data as $row) {
  224. $obj = new $class ($DB);
  225. $obj->_init ($row);
  226. $ret [$obj->getid ()] = $obj;
  227. }
  228. return $ret;
  229. }
  230. }
Copy Code
  1. Class Databaseobject_user extends Databaseobject
  2. {
  3. Static $userTypes = Array (' member ' = ' member ',
  4. ' Administrator ' = ' Administrator ');
  5. public $profile = null;
  6. public $_newpassword = null;
  7. Public function __construct ($DB)
  8. {
  9. Parent::__construct ($db, ' users ', ' user_id ');
  10. $this->add (' username ');
  11. $this->add (' password ');
  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 Preinsert ()
  18. {
  19. $this->_newpassword = text_password::create (8);
  20. $this->password = $this->_newpassword;
  21. return true;
  22. }
  23. protected function Postload ()
  24. {
  25. $this->profile->setuserid ($this->getid ());
  26. $this->profile->load ();
  27. }
  28. protected function Postinsert ()
  29. {
  30. $this->profile->setuserid ($this->getid ());
  31. $this->profile->save (FALSE);
  32. $this->sendemail (' User-register.tpl ');
  33. return true;
  34. }
  35. protected function Postupdate ()
  36. {
  37. $this->profile->save (FALSE);
  38. return true;
  39. }
  40. protected function Predelete ()
  41. {
  42. $this->profile->delete ();
  43. return true;
  44. }
  45. Public Function SendEmail ($TPL)
  46. {
  47. $templater = new Templater ();
  48. $templater->user = $this;
  49. Fetch the e-mail body
  50. $body = $templater->render (' email/'. $tpl);
  51. Extract the subject from the first line
  52. List ($subject, $body) = Preg_split ('/\r|\n/', $body, 2);
  53. Now set up and send the e-mail
  54. $mail = new Zend_mail ();
  55. Set the to address and the user's full name in the "to" line
  56. $mail->addto ($this->profile->email,
  57. Trim ($this->profile->first_name. ' ' .
  58. $this->profile->last_name));
  59. Get the admin ' from ' details from the Config
  60. $mail->setfrom (zend_registry::get (' config ')->email->from->email,
  61. Zend_registry::get (' config ')->email->from->name);
  62. Set the subject and body and send the mail
  63. $mail->setsubject (Trim ($subject));
  64. $mail->setbodytext (Trim ($body));
  65. $mail->send ();
  66. }
  67. Public Function createauthidentity ()
  68. {
  69. $identity = new StdClass;
  70. $identity->user_id = $this->getid ();
  71. $identity->username = $this->username;
  72. $identity->user_type = $this->user_type;
  73. $identity->first_name = $this->profile->first_name;
  74. $identity->last_name = $this->profile->last_name;
  75. $identity->email = $this->profile->email;
  76. return $identity;
  77. }
  78. Public Function loginsuccess ()
  79. {
  80. $this->ts_last_login = time ();
  81. unset ($this->profile->new_password);
  82. unset ($this->profile->new_password_ts);
  83. unset ($this->profile->new_password_key);
  84. $this->save ();
  85. $message = sprintf (' Successful login attempt from%s user%s ',
  86. $_server[' REMOTE_ADDR '),
  87. $this->username);
  88. $logger = Zend_registry::get (' logger ');
  89. $logger->notice ($message);
  90. }
  91. static public Function Loginfailure ($username, $code = ")
  92. {
  93. Switch ($code) {
  94. Case Zend_auth_result::failure_identity_not_found:
  95. $reason = ' Unknown username ';
  96. Break
  97. Case Zend_auth_result::failure_identity_ambiguous:
  98. $reason = ' Multiple users found with this username ';
  99. Break
  100. Case Zend_auth_result::failure_credential_invalid:
  101. $reason = ' Invalid password ';
  102. Break
  103. Default
  104. $reason = ";
  105. }
  106. $message = sprintf (' Failed login attempt from%s user%s ',
  107. $_server[' REMOTE_ADDR '),
  108. $username);
  109. if (strlen ($reason) > 0)
  110. $message. = sprintf (' (%s) ', $reason);
  111. $logger = Zend_registry::get (' logger ');
  112. $logger->warn ($message);
  113. }
  114. Public Function Fetchpassword ()
  115. {
  116. if (! $this->issaved ())
  117. return false;
  118. Generate New Password properties
  119. $this->_newpassword = text_password::create (8);
  120. $this->profile->new_password = MD5 ($this->_newpassword);
  121. $this->profile->new_password_ts = time ();
  122. $this->profile->new_password_key = MD5 (Uniqid ().
  123. $this->getid ().
  124. $this->_newpassword);
  125. Save new password to profile and send e-mail
  126. $this->profile->save ();
  127. $this->sendemail (' User-fetch-password.tpl ');
  128. return true;
  129. }
  130. Public Function Confirmnewpassword ($key)
  131. {
  132. Check that valid password reset data is set
  133. if (!isset ($this->profile->new_password)
  134. || !isset ($this->profile->new_password_ts)
  135. || !isset ($this->profile->new_password_key)) {
  136. return false;
  137. }
  138. Check if the password is being confirm within a day
  139. if (Time ()-$this->profile->new_password_ts > 86400)
  140. return false;
  141. Check the key is correct
  142. if ($this->profile->new_password_key! = $key)
  143. return false;
  144. Everything is valid, now update the account to use the new password
  145. Bypass the local setter as New_password is already an MD5
  146. Parent::__set (' Password ', $this->profile->new_password);
  147. unset ($this->profile->new_password);
  148. unset ($this->profile->new_password_ts);
  149. unset ($this->profile->new_password_key);
  150. Finally, save the updated user record and the updated profile
  151. return $this->save ();
  152. }
  153. Public Function usernameexists ($username)
  154. {
  155. $query = sprintf (' Select COUNT (*) as num from%s where username =? ',
  156. $this->_table);
  157. $result = $this->_db->fetchone ($query, $username);
  158. return $result > 0;
  159. }
  160. static public Function IsValidUserName ($username)
  161. {
  162. $validator = new Zend_validate_alnum ();
  163. Return $validator->isvalid ($username);
  164. }
  165. Public Function __set ($name, $value)
  166. {
  167. Switch ($name) {
  168. Case ' password ':
  169. $value = MD5 ($value);
  170. Break
  171. Case ' User_type ':
  172. if (!array_key_exists ($value, Self:: $userTypes))
  173. $value = ' member ';
  174. Break
  175. }
  176. Return Parent::__set ($name, $value);
  177. }
  178. }
  179. ?>
Copy Code
  • Related Article

    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.