QuentinZervaas & apos; sDBO

Source: Internet
Author: User
QuentinZervaas & amp; apos; sDBO
Quentin Zervaas, author of Web 2.0 development practices, is a simple PHP Data Access Object.

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

  1. Class DatabaseObject_User extends DatabaseObject
  2. {
  3. Static $ userTypes = array ('member' => 'member ',
  4. 'Admin' => 'admin ');
  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 that 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. ?>

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.