Home > Backend Development > PHP Tutorial > Ultra-light PHP database toolkit

Ultra-light PHP database toolkit

WBOY
Release: 2016-07-25 09:09:49
Original
1919 people have browsed it
A very light PHP database toolkit, born two days ago (which is enough to prove that it is very light ).
Two classes, one Connection manages PDO connections (supports multiple databases), and one QuickQuery is used to quickly perform database operations (no need to toss back and forth between PDO and PDOStatement)
No need to download, you can watch it online.
  1. use PersistenceDbAccess;
  2. //Add connection information where the framework is initialized
  3. DbAccessConnection::add(
  4. 'default',
  5. 'sqlite',
  6. '/db/mydb.sqlite',
  7. null, null, false
  8. );
  9. // The following is using
  10. $conn = DbAccessConnection::instance('default');
  11. // Query
  12. $query = new DbAccessQuickQuery($conn);
  13. $query->prepare(' select :name as name')->execute(array(':name'=>'tonyseek'));
  14. // The object directly acts as an iterator to generate a data array
  15. foreach($query as $i) {
  16. var_dump($i);
  17. }
  18. // If you are paranoid, manually disconnect before outputting the response
  19. DbAccessConnection::disconnectAll();
Copy code
  1. namespace PersistenceDbAccess;
  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 PersistenceDbAccessConnection
  20. */
  21. private $connection = null;
  22. /**
  23. * PDO Statement
  24. *
  25. * @var PDOStatement
  26. */
  27. private $stmt = null;
  28. /**
  29. * Checked parameter set
  30. *
  31. * @var array
  32. */
  33. private $checkedParams = array();
  34. /* *
  35. * Construct query channel
  36. *
  37. * @param PersistenceDbAccessConnection $connection database connection
  38. */
  39. public function __construct(Connection $connection)
  40. {
  41. $this->connection = $connection;
  42. }
  43. /**
  44. * Precompiled SQL statement
  45. *
  46. * @param string $sqlCommand SQL statement
  47. * @return PersistenceDbAccessQuickQuery
  48. */
  49. public function prepare($sqlCommand)
  50. {
  51. // Obtain PDO from the connection and execute prepare on the SQL statement to generate PDO Statement
  52. $this->stmt = $this->connection->getPDO()->prepare($sqlCommand);
  53. // Modify the PDO Statement mode to associative 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 PersistenceDbAccessQuickQuery
  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. // Correspond PHP data type to 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 parameter checks
  96. return $this;
  97. }
  98. /**
  99. * Get Statement object
  100. *
  101. * The returned object can be re-executed with bound parameters, or can be used as an iterator to traverse and obtain data.
  102. *
  103. * @return PDOStatement
  104. */
  105. public function getStatement()
  106. {
  107. if (!$this->stmt) {
  108. throw new LogicException('SQL statement should be QuickQuery.prepare first Preprocessing');
  109. }
  110. return $this->stmt;
  111. }
  112. /**
  113. * Alternative name for the getStatement method
  114. *
  115. * Implements the IteratorAggregate interface in the PHP standard library, and external parties can directly use this object as an iterator to traverse
  116. *. The only difference from getStatment is that this method does not throw LogicException. If
  117. * prepare and execute are not used beforehand, an empty iterator will be 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. * Checked query parameters imported here, if not assigned , then a LogicException will be thrown during query.
  133. *
  134. * @param array $params
  135. * @return PersistenceDbAccessQuickQuery
  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. * Get the ID of the last inserted 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 PersistenceDbAccess;
  2. use InvalidArgumentException, BadMethodCallException;
  3. use PDO, PDOException;
  4. /**
  5. * Connection factory, provides global PDO objects, and manages 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 (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. * Username
  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 connections
  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 in transaction
  66. *
  67. * @var bool
  68. */
  69. private $isInTransation = false;
  70. /**
  71. * Private constructor, preventing external instantiation using the new operator
  72. */
  73. private function __construct(){}
  74. /* *
  75. * Production Connector instance (multiple instances)
  76. *
  77. * @param string $name
  78. * @return StuCampusDataModelConnector
  79. */
  80. static public function getInstance($name = 'default')
  81. {
  82. if (!isset(self::$instances[$name])) {
  83. // Throws if the accessed instance does not exist An error occurred
  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 database
  99. *
  100. * Add Connector to the instance group
  101. *
  102. * @param string $name identification name
  103. * @param string $driver 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 Whether to persist the 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 If the name already exists, an exception will be thrown
  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 whether PDO has been instantiated, otherwise instantiate PDO first
  134. $this->pdo = new PDO($this->dsn, $this->username, $ this->password);
  135. // The error mode is to throw a PDOException exception
  136. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  137. // Enable query caching
  138. $this- >pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->isEmulate);
  139. // Enable persistent connections
  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 translationBegin()
  157. {
  158. $this->isInTransation = $this->getPDO()->beginTransaction();
  159. }
  160. /**
  161. * Submit 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. * Rollback transaction
  173. * @return bool
  174. */
  175. public function translationRollback()
  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 $autoRollback Whether to automatically roll back when an exception occurs
  197. * @throws PDOException
  198. * @return bool
  199. */
  200. public function transationExecute($callback, $autoRollback = true)
  201. {
  202. try {
  203. // Start 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 the transaction
  212. return $this->transationCommit();
  213. } catch(PDOException $pex) {
  214. // If automatic rollback is enabled, Then when catching the PDO exception, roll it back first and then throw it
  215. if ($autoRollback) {
  216. $this->transationRollback();
  217. }
  218. throw $pex;
  219. }
  220. }
  221. /**
  222. * Safely disconnect from database
  223. */
  224. public function disconnect()
  225. {
  226. if ($this->pdo) {
  227. // Check whether PDO has been instantiated, if so, set it 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


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template