Home Backend Development PHP Tutorial Ultra-light PHP database toolkit

Ultra-light PHP database toolkit

Jul 25, 2016 am 09:09 AM

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


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles