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.
- Use Persistence \ DbAccess;
- // Add the connection information at the place where the framework is initialized
- DbAccess \ Connection: add (
- 'Default ',
- 'Sqlite ',
- '/Db/mydb. sqlite ',
- Null, null, false
- );
- // Use
- $ Conn = DbAccess \ Connection: instance ('default ');
- // Query
- $ Query = new DbAccess \ QuickQuery ($ conn );
- $ Query-> prepare ('select: name as name')-> execute (array (': name' => 'tonyseek '));
- // The object is directly used as an iterator to generate an array of data
- Foreach ($ query as $ I ){
- Var_dump ($ I );
- }
- // If you are paranoid, manually disconnect the connection before the response is returned.
- DbAccess \ Connection: disconnectAll ();
- Namespace Persistence \ DbAccess;
- Use PDO, ArrayObject, DateTime;
- Use LogicException, InvalidArgumentException;
- /**
- * Quick query Channel
- *
- * @ Version 0.3
- * @ Author tonyseek
- * @ Link http://stu.szu.edu.cn
- * @ License http://www.opensource.org/licenses/mit-license.html
- * @ Copyright StuCampus Development Team, Shenzhen University
- *
- */
- Class QuickQuery implements \ IteratorAggregate
- {
- /**
- * Database connection
- *
- * @ Var \ Persistence \ DbAccess \ Connection
- */
- Private $ connection = null;
-
- /**
- * PDO Statement
- *
- * @ Var PDOStatement
- */
- Private $ stmt = null;
-
- /**
- * Parameter set to be checked
- *
- * @ Var array
- */
- Private $ checkedParams = array ();
-
-
- /**
- * Construct a query Channel
- *
- * @ Param \ Persistence \ DbAccess \ Connection $ connection database Connection
- */
- Public function _ construct (Connection $ connection)
- {
- $ This-> connection = $ connection;
- }
-
- /**
- * Pre-compiled SQL statements
- *
- * @ Param string $ sqlCommand SQL statement
- * @ Return \ Persistence \ DbAccess \ QuickQuery
- */
- Public function prepare ($ sqlCommand)
- {
- // Obtain the PDO from the connection and execute prepare on the SQL Statement to generate the PDO Statement
- $ This-> stmt = $ this-> connection-> getPDO ()-> prepare ($ sqlCommand );
- // Modify the PDO Statement mode to associate array data
- $ This-> stmt-> setFetchMode (PDO: FETCH_ASSOC );
- // Return method chain
- Return $ this;
- }
-
- /**
- * Execute data query
- *
- * @ Throws PDOException
- * @ Return \ Persistence \ DbAccess \ QuickQuery
- */
- Public function execute ($ params = array ())
- {
- $ Stmt = $ this-> getStatement ();
-
- // Parameter check
- $ Diff = array_diff ($ this-> checkedParams, array_keys ($ params ));
- If (count ($ this-> checkedParams) & count ($ diff )){
- Throw new InvalidArgumentException ('required parameter missing:'. implode ('|', $ diff ));
- }
-
- // Map the PHP Data type to the database data type
- Foreach ($ params as $ key => $ value ){
- $ Type = null;
- Switch (true ){
- Case is_int ($ value ):
- $ Type = PDO: PARAM_INT;
- Break;
- Case is_bool ($ value ):
- $ Type = PDO: PARAM_BOOL;
- Break;
- Case ($ value instanceof DateTime ):
- $ Type = PDO: PARAM_STR;
- $ Value = $ value-> format (\ DateTime: W3C );
- Break;
- Case is_null ($ value ):
- $ Type = PDO: PARAM_NULL;
- Break;
- Default:
- $ Type = PDO: PARAM_STR;
- }
-
- $ Stmt-> bindValue ($ key, $ value, $ type );
- }
-
- $ Stmt-> execute ();
- $ This-> checkedParams = array (); // clear the parameter check
- Return $ this;
- }
-
- /**
- * Get the Statement object
- *
- * The Returned object can be re-executed by bound parameters or retrieved as an iterator.
- *
- * @ Return \ PDOStatement
- */
- Public function getStatement ()
- {
- If (! $ This-> stmt ){
- Throw new LogicException ('SQL statement should be preconditioned by QuickQuery. prepare ');
- }
-
- Return $ this-> stmt;
- }
-
- /**
- * Substitution name of the getStatement method
- *
- * Implements the IteratorAggregate interface in the PHP Standard Library. this object can be used as an iterator externally.
- * Calendar. The only difference from getStatment is that this method does not throw a LogicException. If
- * If prepare and execute are not used in advance, an empty iterator is returned.
- *
- * @ Return Traversable
- */
- Public function getIterator ()
- {
- Try {
- Return $ this-> getStatement ();
- } Catch (LogicException $ ex ){
- Return new \ ArrayObject ();
- }
- }
-
- /**
- * Set query parameter check
- *
- * The queried parameters imported here are checked. If no value is assigned, LogicException is thrown during query.
- *
- * @ Param array $ params
- * @ Return \ Persistence \ DbAccess \ QuickQuery
- */
- Public function setParamsCheck (array $ params)
- {
- $ This-> checkedParams = $ params;
-
- Return $ this;
- }
-
- /**
- * Convert the result set to an array
- *
- * @ Return array
- */
- Public function toArray ()
- {
- Return iterator_to_array ($ this-> getStatement ());
- }
-
- /**
- * Obtain the ID of the last insert result (or sequence ).
- *
- * @ Param string $ name
- * @ Return int
- */
- Public function getLastInsertId ($ name = null)
- {
- Return $ this-> connection-> getPDO ()-> lastInsertId ($ name );
- }
- }
- Namespace Persistence \ DbAccess;
- Use InvalidArgumentException, BadMethodCallException;
- Use PDO, PDOException;
- /**
- * Connect to the factory, provide global PDO objects, and manage transactions.
- *
- * @ Version 0.3
- * @ Author tonyseek
- * @ Link http://stu.szu.edu.cn
- * @ License http://www.opensource.org/licenses/mit-license.html
- * @ Copyright StuCampus Development Team, Shenzhen University
- *
- */
- Final class Connection
- {
- /**
- * Connector instance set
- *
- * @ Var array
- */
- Static private $ instances = array ();
- /**
- * Database driver name
- *
- * @ Var string
- */
- Private $ driver = '';
- /**
- * Database Source Name)
- *
- * @ Var string
- */
- Private $ dsn = '';
- /**
- * PDO instance
- *
- * @ Var \ PDO
- */
- Private $ pdo = null;
- /**
- * User name
- *
- * @ Var string
- */
- Private $ username = '';
- /**
- * Password
- *
- * @ Var string
- */
- Private $ password = '';
- /**
- * Whether to enable persistent connection
- *
- * @ Var bool
- */
- Private $ isPersisten = false;
- /**
- * Whether to enable simulation pre-compilation
- *
- * @ Var bool
- */
- Private $ isEmulate = false;
- /**
- * Whether the transaction is in progress
- *
- * @ Var bool
- */
- Private $ isInTransation = false;
- /**
- * Private constructor prevents external entities from instantiating using the new operator
- */
- Private function _ construct (){}
- /**
- * Producing Connector instances (multiple instances)
- *
- * @ Param string $ name
- * @ Return \ StuCampus \ DataModel \ Connector
- */
- Static public function getInstance ($ name = 'default ')
- {
- If (! Isset (self: $ instances [$ name]) {
- // If the Accessed instance does not exist, an error is thrown.
- Throw new InvalidArgumentException ("[{$ name}] does not exist ");
- }
- Return self: $ instances [$ name];
- }
- /**
- * Disconnect all database instances
- */
- Static public function disconnectAll ()
- {
- Foreach (self: $ instances as $ instance ){
- $ Instance-> disconnect ();
- }
- }
- /**
- * Add a database
- *
- * Add Connector to the instance Group
- *
- * @ Param string $ name: name
- * @ Param string $ driver name
- * @ Param string $ dsn connection string
- * @ Param string $ usr database username
- * @ Param string $ pwd database password
- * @ Param bool $ emulate simulation precompiled query
- * @ Param bool $ persisten persistent connection
- */
- Static public function registry ($ name, $ driver, $ dsn, $ usr, $ pwd, $ emulate = false, $ persisten = false)
- {
- If (isset (self: $ instances [$ name]) {
- // If the added instance name already exists, an exception is thrown.
- Throw new BadMethodCallException ("[{$ name}] registered ");
- }
- // Instantiate itself and push it into the array
- Self: $ instances [$ name] = new self ();
- Self: $ instances [$ name]-> dsn = $ driver. ':'. $ dsn;
- Self: $ instances [$ name]-> username = $ usr;
- Self: $ instances [$ name]-> password = $ pwd;
- Self: $ instances [$ name]-> driver = $ driver;
- Self: $ instances [$ name]-> isPersisten = (bool) $ persisten;
- Self: $ instances [$ name]-> isEmulate = (bool) $ emulate;
- }
- /**
- * Getting PHP Database objects
- *
- * @ Return \ PDO
- */
- Public function getPDO ()
- {
- If (! $ This-> pdo ){
- // Check whether the PDO has been instantiated. Otherwise, the PDO is instantiated first.
- $ This-> pdo = new PDO ($ this-> dsn, $ this-> username, $ this-> password );
- // The error mode is to throw a PDOException
- $ This-> pdo-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION );
- // Enable query cache
- $ This-> pdo-> setAttribute (PDO: ATTR_EMULATE_PREPARES, $ this-> isEmulate );
- // Enable persistent connection
- $ This-> pdo-> setAttribute (PDO: ATTR_PERSISTENT, $ this-> isPersisten );
- }
- Return $ this-> pdo;
- }
- /**
- * Get the database driver name
- *
- * @ Return string
- */
- Public function getDriverName ()
- {
- Return $ this-> driver;
- }
- /**
- * Start transaction
- */
- Public function transationBegin ()
- {
- $ This-> isInTransation = $ this-> getPDO ()-> beginTransaction ();
- }
- /**
- * Submit a transaction.
- */
- Public function transationCommit ()
- {
- If ($ this-> isInTransation ){
- $ This-> getPDO ()-> commit ();
- } Else {
- Trigger_error ('transationbegin should be called before transationCommit ');
- }
- }
- /**
- * Roll back a transaction
- * @ Return bool
- */
- Public function transationRollback ()
- {
- If ($ this-> isInTransation ){
- $ This-> getPDO ()-> rollBack ();
- } Else {
- Trigger_error ('transationbegin should be called before transationrollback ');
- }
- }
- /**
- * Whether the connection is in the transaction
- *
- * @ Return bool
- */
- Public function isInTransation ()
- {
- Return $ this-> isInTransation;
- }
- /**
- * Execute the callback function in the transaction.
- *
- * @ Param function $ callback anonymous function or closure function
- * @ Param bool $ whether to roll back automatically when an autoRollback exception occurs
- * @ Throws \ PDOException
- * @ Return bool
- */
- Public function transationExecute ($ callback, $ autoRollback = true)
- {
- Try {
- // Start the transaction
- $ This-> transationBegin ();
- // Call the callback function
- If (is_callable ($ callback )){
- $ Callback ();
- } Else {
- Throw new InvalidArgumentException ('$ callback should be the callback function ');
- }
- // Submit the transaction
- Return $ this-> transationCommit ();
- } Catch (PDOException $ pex ){
- // If automatic rollback is enabled, rollback is performed before it is thrown when a PDO exception is caught.
- If ($ autoRollback ){
- $ This-> transationRollback ();
- }
- Throw $ pex;
- }
- }
- /**
- * Securely disconnect the database
- */
- Public function disconnect ()
- {
- If ($ this-> pdo ){
- // Check whether PDO has been instantiated. If yes, it is set to null.
- $ This-> pdo = null;
- }
- }
- /**
- * Stop cloning
- */
- Public function _ clone ()
- {
- Trigger_error ('blocked _ clone method, Connector is a singleton class ');
- }
- }
|