Ultra-Lightweight PHP Database Toolkit

Source: Internet
Author: User
Tags diff dsn php database
A very light PHP database toolkit, born in two days (enough to prove very light).
Two classes, one Connection management PDO connection (multi-database support), one quickquery for fast database operation (no back-and-forth between PDO and Pdostatement)
You can read it online without downloading it.
    1. Use persistence\dbaccess;
    2. Add connection information where the framework is initialized
    3. Dbaccess\connection::add (
    4. ' Default ',
    5. ' SQLite ',
    6. '/db/mydb.sqlite ',
    7. NULL, NULL, FALSE
    8. );
    9. Here's how to use
    10. $conn = dbaccess\connection::instance (' default ');
    11. Inquire
    12. $query = new Dbaccess\quickquery ($conn);
    13. $query->prepare (' Select:name as Name ')->execute (Array (': Name ' = ' Tonyseek '));
    14. object to produce an array of data directly as an iterator
    15. foreach ($query as $i) {
    16. Var_dump ($i);
    17. }
    18. If there is paranoia, the output response is manually disconnected before
    19. Dbaccess\connection::d isconnectall ();
Copy Code
  1. namespace Persistence\dbaccess;
  2. Use PDO, Arrayobject, DateTime;
  3. Use Logicexception, invalidargumentexception;
  4. /**
  5. * Fast 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. * Set of parameters to be checked
  30. *
  31. * @var Array
  32. */
  33. Private $checkedParams = Array ();
  34. /**
  35. * Construct 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. * Precompiled SQL statements
  45. *
  46. * @param string $sqlCommand SQL statement
  47. * @return \persistence\dbaccess\quickquery
  48. */
  49. Public function prepare ($sqlCommand)
  50. {
  51. Gets the PDO from the connection and executes the prepare on the SQL statement, producing the PDO Statement
  52. $this->stmt = $this->connection->getpdo ()->prepare ($sqlCommand);
  53. modifying PDO Statement mode for associative array data
  54. $this->stmt->setfetchmode (PDO::FETCH_ASSOC);
  55. Return to Method chain
  56. return $this;
  57. }
  58. /**
  59. * Perform 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 (' missing required parameter: '. Implode (') ' | ', $diff));
  71. }
  72. To 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::P aram_int;
  78. Break
  79. Case Is_bool ($value):
  80. $type = PDO::P aram_bool;
  81. Break
  82. Case ($value instanceof DateTime):
  83. $type = PDO::P aram_str;
  84. $value = $value->format (\DATETIME::W3C);
  85. Break
  86. Case Is_null ($value):
  87. $type = PDO::P aram_null;
  88. Break
  89. Default
  90. $type = PDO::P aram_str;
  91. }
  92. $stmt->bindvalue ($key, $value, $type);
  93. }
  94. $stmt->execute ();
  95. $this->checkedparams = Array (); Clear parameter Check
  96. return $this;
  97. }
  98. /**
  99. * Get Statement Object
  100. *
  101. * The returned object can be re-executed by the binding parameter, or it can be traversed as an iterator to fetch the data.
  102. *
  103. * @return \pdostatement
  104. */
  105. Public Function getstatement ()
  106. {
  107. if (! $this->stmt) {
  108. throw new Logicexception (' SQL statements should be quickquery.prepare preprocessed first ');
  109. }
  110. return $this->stmt;
  111. }
  112. /**
  113. * Alternative name for the Getstatement method
  114. *
  115. * Implement Iteratoraggregate interface in PHP Standard library, external can directly use this object as an iterator
  116. Calendar The only difference with getstatment is that this method does not throw logicexception exceptions. If
  117. * An empty iterator is returned without using prepare and execute in advance.
  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 checked query parameters are imported here, and if they are not assigned, the Logicexception exception is thrown when queried.
  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 result set to array
  144. *
  145. * @return Array
  146. */
  147. Public Function ToArray ()
  148. {
  149. Return Iterator_to_array ($this->getstatement ());
  150. }
  151. /**
  152. * Gets 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. }
Copy Code
  1. namespace Persistence\dbaccess;
  2. Use InvalidArgumentException, badmethodcallexception;
  3. Use PDO, pdoexception;
  4. /**
  5. * Connect factories, 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 Collection
  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 connection string (db 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 turn on persistent connection
  54. *
  55. * @var BOOL
  56. */
  57. Private $isPersisten = false;
  58. /**
  59. * Whether to turn on emulation precompilation
  60. *
  61. * @var BOOL
  62. */
  63. Private $isEmulate = false;
  64. /**
  65. * Whether in the transaction
  66. *
  67. * @var BOOL
  68. */
  69. Private $isInTransation = false;
  70. /**
  71. * Private constructor to prevent external instantiation using the new operator
  72. */
  73. Private Function __construct () {}
  74. /**
  75. * Production Connector instances (multiple cases)
  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. Throws an error exception if the accessed instance does not exist
  84. throw new InvalidArgumentException ("[{$name}] does not exist");
  85. }
  86. Return self:: $instances [$name];
  87. }
  88. /**
  89. * Disconnect All DB instances
  90. */
  91. static public Function Disconnectall ()
  92. {
  93. foreach (self:: $instances as $instance) {
  94. $instance->disconnect ();
  95. }
  96. }
  97. /**
  98. * Add Database
  99. *
  100. * Add Connector to the instance group
  101. *
  102. * @param string $name identity name
  103. * @param string $driver driver name
  104. * @param string $DSN connection string
  105. * @param string $usr database user name
  106. * @param string $pwd database Password
  107. * @param bool $emulate emulation 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. Throws an exception if the added instance name already exists
  114. throw new Badmethodcallexception ("[{$name}] has been 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. * Get PHP Database Object
  127. *
  128. * @return \pdo
  129. */
  130. Public Function Getpdo ()
  131. {
  132. if (! $this->pdo) {
  133. Check if PDO is instantiated, or instantiate PDO first
  134. $this->pdo = new PDO ($this->dsn, $this->username, $this->password);
  135. Error mode throws a Pdoexception exception
  136. $this->pdo->setattribute (Pdo::attr_errmode, pdo::errmode_exception);
  137. Turn on query caching
  138. $this->pdo->setattribute (pdo::attr_emulate_prepares, $this->isemulate);
  139. Turn on persistent connections
  140. $this->pdo->setattribute (pdo::attr_persistent, $this->ispersisten);
  141. }
  142. return $this->pdo;
  143. }
  144. /**
  145. * Get Database driver name
  146. *
  147. * @return String
  148. */
  149. Public Function Getdrivername ()
  150. {
  151. return $this->driver;
  152. }
  153. /**
  154. * Start a transaction
  155. */
  156. Public Function Transationbegin ()
  157. {
  158. $this->isintransation = $this->getpdo ()->begintransaction ();
  159. }
  160. /**
  161. * Commit a transaction
  162. */
  163. Public Function Transationcommit ()
  164. {
  165. if ($this->isintransation) {
  166. $this->getpdo ()->commit ();
  167. } else {
  168. Trigger_error (' Transationbegin should be preceded by transationcommit call ');
  169. }
  170. }
  171. /**
  172. * ROLLBACK 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 preceded by transationrollback call ');
  181. }
  182. }
  183. /**
  184. * Whether the connection is in a transaction
  185. *
  186. * @return BOOL
  187. */
  188. Public Function isintransation ()
  189. {
  190. return $this->isintransation;
  191. }
  192. /**
  193. * Execute callback function in transaction
  194. *
  195. * @param function $callback anonymous functions or closure functions
  196. * Whether to automatically roll back when @param bool $autoRollback exception occurs
  197. * @throws \pdoexception
  198. * @return BOOL
  199. */
  200. Public Function Transationexecute ($callback, $autoRollback = True)
  201. {
  202. try {
  203. Start a transaction
  204. $this->transationbegin ();
  205. Call callback function
  206. if (is_callable ($callback)) {
  207. $callback ();
  208. } else {
  209. throw new InvalidArgumentException (' $callback should be a callback function ');
  210. }
  211. Commit a transaction
  212. return $this->transationcommit ();
  213. } catch (Pdoexception $pex) {
  214. If automatic rollback is turned on, the snapping to the PDO exception is rolled back before it is thrown
  215. if ($autoRollback) {
  216. $this->transationrollback ();
  217. }
  218. Throw $pex;
  219. }
  220. }
  221. /**
  222. * Securely disconnecting database connections
  223. */
  224. Public Function Disconnect ()
  225. {
  226. if ($this->pdo) {
  227. Check if PDO has been instantiated, yes set to NULL
  228. $this->pdo = null;
  229. }
  230. }
  231. /**
  232. * Block cloning
  233. */
  234. Public Function __clone ()
  235. {
  236. Trigger_error (' blocked __clone method, Connector is a singleton class ');
  237. }
  238. }
Copy Code
  • 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.