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.
- Use persistence\dbaccess;
- Add connection information where the framework is initialized
- Dbaccess\connection::add (
- ' Default ',
- ' SQLite ',
- '/db/mydb.sqlite ',
- NULL, NULL, FALSE
- );
- Here's how to use
- $conn = dbaccess\connection::instance (' default ');
- Inquire
- $query = new Dbaccess\quickquery ($conn);
- $query->prepare (' Select:name as Name ')->execute (Array (': Name ' = ' Tonyseek '));
- object to produce an array of data directly as an iterator
- foreach ($query as $i) {
- Var_dump ($i);
- }
- If there is paranoia, the output response is manually disconnected before
- Dbaccess\connection::d isconnectall ();
Copy Code
- namespace Persistence\dbaccess;
- Use PDO, Arrayobject, DateTime;
- Use Logicexception, invalidargumentexception;
- /**
- * Fast 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;
- /**
- * Set of parameters to be checked
- *
- * @var Array
- */
- Private $checkedParams = Array ();
- /**
- * Construct query Channel
- *
- * @param \persistence\dbaccess\connection $connection database connection
- */
- Public function __construct (Connection $connection)
- {
- $this->connection = $connection;
- }
- /**
- * Precompiled SQL statements
- *
- * @param string $sqlCommand SQL statement
- * @return \persistence\dbaccess\quickquery
- */
- Public function prepare ($sqlCommand)
- {
- Gets the PDO from the connection and executes the prepare on the SQL statement, producing the PDO Statement
- $this->stmt = $this->connection->getpdo ()->prepare ($sqlCommand);
- modifying PDO Statement mode for associative array data
- $this->stmt->setfetchmode (PDO::FETCH_ASSOC);
- Return to Method chain
- return $this;
- }
- /**
- * Perform 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 (' missing required parameter: '. Implode (') ' | ', $diff));
- }
- To 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::P aram_int;
- Break
- Case Is_bool ($value):
- $type = PDO::P aram_bool;
- Break
- Case ($value instanceof DateTime):
- $type = PDO::P aram_str;
- $value = $value->format (\DATETIME::W3C);
- Break
- Case Is_null ($value):
- $type = PDO::P aram_null;
- Break
- Default
- $type = PDO::P aram_str;
- }
- $stmt->bindvalue ($key, $value, $type);
- }
- $stmt->execute ();
- $this->checkedparams = Array (); Clear parameter Check
- return $this;
- }
- /**
- * Get Statement Object
- *
- * The returned object can be re-executed by the binding parameter, or it can be traversed as an iterator to fetch the data.
- *
- * @return \pdostatement
- */
- Public Function getstatement ()
- {
- if (! $this->stmt) {
- throw new Logicexception (' SQL statements should be quickquery.prepare preprocessed first ');
- }
- return $this->stmt;
- }
- /**
- * Alternative name for the Getstatement method
- *
- * Implement Iteratoraggregate interface in PHP Standard library, external can directly use this object as an iterator
- Calendar The only difference with getstatment is that this method does not throw logicexception exceptions. If
- * An empty iterator is returned without using prepare and execute in advance.
- *
- * @return traversable
- */
- Public Function Getiterator ()
- {
- try {
- return $this->getstatement ();
- } catch (Logicexception $ex) {
- return new \arrayobject ();
- }
- }
- /**
- * Set query parameter check
- *
- * The checked query parameters are imported here, and if they are not assigned, the Logicexception exception is thrown when queried.
- *
- * @param array $params
- * @return \persistence\dbaccess\quickquery
- */
- Public function Setparamscheck (array $params)
- {
- $this->checkedparams = $params;
- return $this;
- }
- /**
- * Convert result set to array
- *
- * @return Array
- */
- Public Function ToArray ()
- {
- Return Iterator_to_array ($this->getstatement ());
- }
- /**
- * Gets 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);
- }
- }
Copy Code
- namespace Persistence\dbaccess;
- Use InvalidArgumentException, badmethodcallexception;
- Use PDO, pdoexception;
- /**
- * Connect factories, 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 Collection
- *
- * @var Array
- */
- static Private $instances = Array ();
- /**
- * Database driver name
- *
- * @var String
- */
- Private $driver = ';
- /**
- * Database connection string (db 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 turn on persistent connection
- *
- * @var BOOL
- */
- Private $isPersisten = false;
- /**
- * Whether to turn on emulation precompilation
- *
- * @var BOOL
- */
- Private $isEmulate = false;
- /**
- * Whether in the transaction
- *
- * @var BOOL
- */
- Private $isInTransation = false;
- /**
- * Private constructor to prevent external instantiation using the new operator
- */
- Private Function __construct () {}
- /**
- * Production Connector instances (multiple cases)
- *
- * @param string $name
- * @return \stucampus\datamodel\connector
- */
- static public Function getinstance ($name = ' default ')
- {
- if (!isset (self:: $instances [$name])) {
- Throws an error exception if the accessed instance does not exist
- throw new InvalidArgumentException ("[{$name}] does not exist");
- }
- Return self:: $instances [$name];
- }
- /**
- * Disconnect All DB instances
- */
- static public Function Disconnectall ()
- {
- foreach (self:: $instances as $instance) {
- $instance->disconnect ();
- }
- }
- /**
- * Add Database
- *
- * Add Connector to the instance group
- *
- * @param string $name identity name
- * @param string $driver driver name
- * @param string $DSN connection string
- * @param string $usr database user name
- * @param string $pwd database Password
- * @param bool $emulate emulation 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])) {
- Throws an exception if the added instance name already exists
- throw new Badmethodcallexception ("[{$name}] has been 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;
- }
- /**
- * Get PHP Database Object
- *
- * @return \pdo
- */
- Public Function Getpdo ()
- {
- if (! $this->pdo) {
- Check if PDO is instantiated, or instantiate PDO first
- $this->pdo = new PDO ($this->dsn, $this->username, $this->password);
- Error mode throws a Pdoexception exception
- $this->pdo->setattribute (Pdo::attr_errmode, pdo::errmode_exception);
- Turn on query caching
- $this->pdo->setattribute (pdo::attr_emulate_prepares, $this->isemulate);
- Turn on persistent connections
- $this->pdo->setattribute (pdo::attr_persistent, $this->ispersisten);
- }
- return $this->pdo;
- }
- /**
- * Get Database driver name
- *
- * @return String
- */
- Public Function Getdrivername ()
- {
- return $this->driver;
- }
- /**
- * Start a transaction
- */
- Public Function Transationbegin ()
- {
- $this->isintransation = $this->getpdo ()->begintransaction ();
- }
- /**
- * Commit a transaction
- */
- Public Function Transationcommit ()
- {
- if ($this->isintransation) {
- $this->getpdo ()->commit ();
- } else {
- Trigger_error (' Transationbegin should be preceded by transationcommit call ');
- }
- }
- /**
- * ROLLBACK TRANSACTION
- * @return BOOL
- */
- Public Function Transationrollback ()
- {
- if ($this->isintransation) {
- $this->getpdo ()->rollback ();
- } else {
- Trigger_error (' Transationbegin should be preceded by transationrollback call ');
- }
- }
- /**
- * Whether the connection is in a transaction
- *
- * @return BOOL
- */
- Public Function isintransation ()
- {
- return $this->isintransation;
- }
- /**
- * Execute callback function in transaction
- *
- * @param function $callback anonymous functions or closure functions
- * Whether to automatically roll back when @param bool $autoRollback exception occurs
- * @throws \pdoexception
- * @return BOOL
- */
- Public Function Transationexecute ($callback, $autoRollback = True)
- {
- try {
- Start a transaction
- $this->transationbegin ();
- Call callback function
- if (is_callable ($callback)) {
- $callback ();
- } else {
- throw new InvalidArgumentException (' $callback should be a callback function ');
- }
- Commit a transaction
- return $this->transationcommit ();
- } catch (Pdoexception $pex) {
- If automatic rollback is turned on, the snapping to the PDO exception is rolled back before it is thrown
- if ($autoRollback) {
- $this->transationrollback ();
- }
- Throw $pex;
- }
- }
- /**
- * Securely disconnecting database connections
- */
- Public Function Disconnect ()
- {
- if ($this->pdo) {
- Check if PDO has been instantiated, yes set to NULL
- $this->pdo = null;
- }
- }
- /**
- * Block cloning
- */
- Public Function __clone ()
- {
- Trigger_error (' blocked __clone method, Connector is a singleton class ');
- }
- }
Copy Code |