PHP database Toolkit

Source: Internet
Author: User
PHP database Toolkit
A very lightweight PHP database toolkit was born for two days (enough to prove very lightweight ).
Two classes: one Connection to manage the PDO Connection (supporting multiple databases) and one QuickQuery to quickly perform database operations (no need to go back and forth between PDO and PDOStatement)
You don't need to download it. you can view it online.

  1. Use Persistence \ DbAccess;
  2. // Add the connection information at the place where the framework is initialized
  3. DbAccess \ Connection: add (
  4. 'Default ',
  5. 'Sqlite ',
  6. '/Db/mydb. sqlite ',
  7. Null, null, false
  8. );
  9. // Use
  10. $ Conn = DbAccess \ Connection: instance ('default ');
  11. // Query
  12. $ Query = new DbAccess \ QuickQuery ($ conn );
  13. $ Query-> prepare ('select: name as name')-> execute (array (': name' => 'tonyseek '));
  14. // The object is directly used as an iterator to generate an array of data
  15. Foreach ($ query as $ I ){
  16. Var_dump ($ I );
  17. }
  18. // If you are paranoid, manually disconnect the connection before the response is returned.
  19. DbAccess \ Connection: disconnectAll ();

  1. Namespace Persistence \ DbAccess;
  2. Use PDO, ArrayObject, DateTime;
  3. Use LogicException, InvalidArgumentException;
  4. /**
  5. * Quick query Channel
  6. *
  7. * @ Version 0.3
  8. * @ Author tonyseek
  9. * @ Link http://stu.szu.edu.cn
  10. * @ License http://www.opensource.org/licenses/mit-license.html
  11. * @ Copyright StuCampus Development Team, Shenzhen University
  12. *
  13. */
  14. Class QuickQuery implements \ IteratorAggregate
  15. {
  16. /**
  17. * Database connection
  18. *
  19. * @ Var \ Persistence \ DbAccess \ Connection
  20. */
  21. Private $ connection = null;
  22. /**
  23. * PDO Statement
  24. *
  25. * @ Var PDOStatement
  26. */
  27. Private $ stmt = null;
  28. /**
  29. * Parameter set to be checked
  30. *
  31. * @ Var array
  32. */
  33. Private $ checkedParams = array ();
  34. /**
  35. * Construct a query Channel
  36. *
  37. * @ Param \ Persistence \ DbAccess \ Connection $ connection database Connection
  38. */
  39. Public function _ construct (Connection $ connection)
  40. {
  41. $ This-> connection = $ connection;
  42. }
  43. /**
  44. * Pre-compiled SQL statements
  45. *
  46. * @ Param string $ sqlCommand SQL statement
  47. * @ Return \ Persistence \ DbAccess \ QuickQuery
  48. */
  49. Public function prepare ($ sqlCommand)
  50. {
  51. // Obtain the PDO from the connection and execute prepare on the SQL Statement to generate the PDO Statement
  52. $ This-> stmt = $ this-> connection-> getPDO ()-> prepare ($ sqlCommand );
  53. // Modify the PDO Statement mode to associate array data
  54. $ This-> stmt-> setFetchMode (PDO: FETCH_ASSOC );
  55. // Return method chain
  56. Return $ this;
  57. }
  58. /**
  59. * Execute data query
  60. *
  61. * @ Throws PDOException
  62. * @ Return \ Persistence \ DbAccess \ QuickQuery
  63. */
  64. Public function execute ($ params = array ())
  65. {
  66. $ Stmt = $ this-> getStatement ();
  67. // Parameter check
  68. $ Diff = array_diff ($ this-> checkedParams, array_keys ($ params ));
  69. If (count ($ this-> checkedParams) & count ($ diff )){
  70. Throw new InvalidArgumentException ('required parameter missing:'. implode ('|', $ diff ));
  71. }
  72. // Map the PHP Data type to the database data type
  73. Foreach ($ params as $ key => $ value ){
  74. $ Type = null;
  75. Switch (true ){
  76. Case is_int ($ value ):
  77. $ Type = PDO: PARAM_INT;
  78. Break;
  79. Case is_bool ($ value ):
  80. $ Type = PDO: PARAM_BOOL;
  81. Break;
  82. Case ($ value instanceof DateTime ):
  83. $ Type = PDO: PARAM_STR;
  84. $ Value = $ value-> format (\ DateTime: W3C );
  85. Break;
  86. Case is_null ($ value ):
  87. $ Type = PDO: PARAM_NULL;
  88. Break;
  89. Default:
  90. $ Type = PDO: PARAM_STR;
  91. }
  92. $ Stmt-> bindValue ($ key, $ value, $ type );
  93. }
  94. $ Stmt-> execute ();
  95. $ This-> checkedParams = array (); // clear the parameter check
  96. Return $ this;
  97. }
  98. /**
  99. * Get the Statement object
  100. *
  101. * The Returned object can be re-executed by bound parameters or retrieved as an iterator.
  102. *
  103. * @ Return \ PDOStatement
  104. */
  105. Public function getStatement ()
  106. {
  107. If (! $ This-> stmt ){
  108. Throw new LogicException ('SQL statement should be preconditioned by QuickQuery. prepare ');
  109. }
  110. Return $ this-> stmt;
  111. }
  112. /**
  113. * Substitution name of the getStatement method
  114. *
  115. * Implements the IteratorAggregate interface in the PHP Standard Library. this object can be used as an iterator externally.
  116. * Calendar. The only difference from getStatment is that this method does not throw a LogicException. If
  117. * If prepare and execute are not used in advance, an empty iterator is returned.
  118. *
  119. * @ Return Traversable
  120. */
  121. Public function getIterator ()
  122. {
  123. Try {
  124. Return $ this-> getStatement ();
  125. } Catch (LogicException $ ex ){
  126. Return new \ ArrayObject ();
  127. }
  128. }
  129. /**
  130. * Set query parameter check
  131. *
  132. * The queried parameters imported here are checked. If no value is assigned, LogicException is thrown during query.
  133. *
  134. * @ Param array $ params
  135. * @ Return \ Persistence \ DbAccess \ QuickQuery
  136. */
  137. Public function setParamsCheck (array $ params)
  138. {
  139. $ This-> checkedParams = $ params;
  140. Return $ this;
  141. }
  142. /**
  143. * Convert the result set to an array
  144. *
  145. * @ Return array
  146. */
  147. Public function toArray ()
  148. {
  149. Return iterator_to_array ($ this-> getStatement ());
  150. }
  151. /**
  152. * Obtain the ID of the last insert result (or sequence ).
  153. *
  154. * @ Param string $ name
  155. * @ Return int
  156. */
  157. Public function getLastInsertId ($ name = null)
  158. {
  159. Return $ this-> connection-> getPDO ()-> lastInsertId ($ name );
  160. }
  161. }

  1. Namespace Persistence \ DbAccess;
  2. Use InvalidArgumentException, BadMethodCallException;
  3. Use PDO, PDOException;
  4. /**
  5. * Connect to the factory, provide global PDO objects, and manage transactions.
  6. *
  7. * @ Version 0.3
  8. * @ Author tonyseek
  9. * @ Link http://stu.szu.edu.cn
  10. * @ License http://www.opensource.org/licenses/mit-license.html
  11. * @ Copyright StuCampus Development Team, Shenzhen University
  12. *
  13. */
  14. Final class Connection
  15. {
  16. /**
  17. * Connector instance set
  18. *
  19. * @ Var array
  20. */
  21. Static private $ instances = array ();
  22. /**
  23. * Database driver name
  24. *
  25. * @ Var string
  26. */
  27. Private $ driver = '';
  28. /**
  29. * Database Source Name)
  30. *
  31. * @ Var string
  32. */
  33. Private $ dsn = '';
  34. /**
  35. * PDO instance
  36. *
  37. * @ Var \ PDO
  38. */
  39. Private $ pdo = null;
  40. /**
  41. * User name
  42. *
  43. * @ Var string
  44. */
  45. Private $ username = '';
  46. /**
  47. * Password
  48. *
  49. * @ Var string
  50. */
  51. Private $ password = '';
  52. /**
  53. * Whether to enable persistent connection
  54. *
  55. * @ Var bool
  56. */
  57. Private $ isPersisten = false;
  58. /**
  59. * Whether to enable simulation pre-compilation
  60. *
  61. * @ Var bool
  62. */
  63. Private $ isEmulate = false;
  64. /**
  65. * Whether the transaction is in progress
  66. *
  67. * @ Var bool
  68. */
  69. Private $ isInTransation = false;
  70. /**
  71. * Private constructor prevents external entities from instantiating using the new operator
  72. */
  73. Private function _ construct (){}
  74. /**
  75. * Producing Connector instances (multiple instances)
  76. *
  77. * @ Param string $ name
  78. * @ Return \ StuCampus \ DataModel \ Connector
  79. */
  80. Static public function getInstance ($ name = 'default ')
  81. {
  82. If (! Isset (self: $ instances [$ name]) {
  83. // If the Accessed instance does not exist, an error is thrown.
  84. Throw new InvalidArgumentException ("[{$ name}] does not exist ");
  85. }
  86. Return self: $ instances [$ name];
  87. }
  88. /**
  89. * Disconnect all database instances
  90. */
  91. Static public function disconnectAll ()
  92. {
  93. Foreach (self: $ instances as $ instance ){
  94. $ Instance-> disconnect ();
  95. }
  96. }
  97. /**
  98. * Add a database
  99. *
  100. * Add Connector to the instance Group
  101. *
  102. * @ Param string $ name: name
  103. * @ Param string $ driver name
  104. * @ Param string $ dsn connection string
  105. * @ Param string $ usr database username
  106. * @ Param string $ pwd database password
  107. * @ Param bool $ emulate simulation precompiled query
  108. * @ Param bool $ persisten persistent connection
  109. */
  110. Static public function registry ($ name, $ driver, $ dsn, $ usr, $ pwd, $ emulate = false, $ persisten = false)
  111. {
  112. If (isset (self: $ instances [$ name]) {
  113. // If the added instance name already exists, an exception is thrown.
  114. Throw new BadMethodCallException ("[{$ name}] registered ");
  115. }
  116. // Instantiate itself and push it into the array
  117. Self: $ instances [$ name] = new self ();
  118. Self: $ instances [$ name]-> dsn = $ driver. ':'. $ dsn;
  119. Self: $ instances [$ name]-> username = $ usr;
  120. Self: $ instances [$ name]-> password = $ pwd;
  121. Self: $ instances [$ name]-> driver = $ driver;
  122. Self: $ instances [$ name]-> isPersisten = (bool) $ persisten;
  123. Self: $ instances [$ name]-> isEmulate = (bool) $ emulate;
  124. }
  125. /**
  126. * Getting PHP Database objects
  127. *
  128. * @ Return \ PDO
  129. */
  130. Public function getPDO ()
  131. {
  132. If (! $ This-> pdo ){
  133. // Check whether the PDO has been instantiated. Otherwise, the PDO is instantiated first.
  134. $ This-> pdo = new PDO ($ this-> dsn, $ this-> username, $ this-> password );
  135. // The error mode is to throw a PDOException
  136. $ This-> pdo-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION );
  137. // Enable query cache
  138. $ This-> pdo-> setAttribute (PDO: ATTR_EMULATE_PREPARES, $ this-> isEmulate );
  139. // Enable persistent connection
  140. $ This-> pdo-> setAttribute (PDO: ATTR_PERSISTENT, $ this-> isPersisten );
  141. }
  142. Return $ this-> pdo;
  143. }
  144. /**
  145. * Get the database driver name
  146. *
  147. * @ Return string
  148. */
  149. Public function getDriverName ()
  150. {
  151. Return $ this-> driver;
  152. }
  153. /**
  154. * Start transaction
  155. */
  156. Public function transationBegin ()
  157. {
  158. $ This-> isInTransation = $ this-> getPDO ()-> beginTransaction ();
  159. }
  160. /**
  161. * Submit a transaction.
  162. */
  163. Public function transationCommit ()
  164. {
  165. If ($ this-> isInTransation ){
  166. $ This-> getPDO ()-> commit ();
  167. } Else {
  168. Trigger_error ('transationbegin should be called before transationCommit ');
  169. }
  170. }
  171. /**
  172. * Roll back a transaction
  173. * @ Return bool
  174. */
  175. Public function transationRollback ()
  176. {
  177. If ($ this-> isInTransation ){
  178. $ This-> getPDO ()-> rollBack ();
  179. } Else {
  180. Trigger_error ('transationbegin should be called before transationrollback ');
  181. }
  182. }
  183. /**
  184. * Whether the connection is in the transaction
  185. *
  186. * @ Return bool
  187. */
  188. Public function isInTransation ()
  189. {
  190. Return $ this-> isInTransation;
  191. }
  192. /**
  193. * Execute the callback function in the transaction.
  194. *
  195. * @ Param function $ callback anonymous function or closure function
  196. * @ Param bool $ whether to roll back automatically when an autoRollback exception occurs
  197. * @ Throws \ PDOException
  198. * @ Return bool
  199. */
  200. Public function transationExecute ($ callback, $ autoRollback = true)
  201. {
  202. Try {
  203. // Start the transaction
  204. $ This-> transationBegin ();
  205. // Call the callback function
  206. If (is_callable ($ callback )){
  207. $ Callback ();
  208. } Else {
  209. Throw new InvalidArgumentException ('$ callback should be the callback function ');
  210. }
  211. // Submit the transaction
  212. Return $ this-> transationCommit ();
  213. } Catch (PDOException $ pex ){
  214. // If automatic rollback is enabled, rollback is performed before it is thrown when a PDO exception is caught.
  215. If ($ autoRollback ){
  216. $ This-> transationRollback ();
  217. }
  218. Throw $ pex;
  219. }
  220. }
  221. /**
  222. * Securely disconnect the database
  223. */
  224. Public function disconnect ()
  225. {
  226. If ($ this-> pdo ){
  227. // Check whether PDO has been instantiated. If yes, it is set to null.
  228. $ This-> pdo = null;
  229. }
  230. }
  231. /**
  232. * Stop cloning
  233. */
  234. Public function _ clone ()
  235. {
  236. Trigger_error ('blocked _ clone method, Connector is a singleton class ');
  237. }
  238. }

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.