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.
- use PersistenceDbAccess;
- //Add connection information where the framework is initialized
- DbAccessConnection::add(
- 'default',
- 'sqlite',
- '/db/mydb.sqlite',
- null, null, false
- );
- // The following is using
- $conn = DbAccessConnection::instance('default');
- // Query
- $query = new DbAccessQuickQuery($conn);
- $query->prepare(' select :name as name')->execute(array(':name'=>'tonyseek'));
- // The object directly acts as an iterator to generate a data array
- foreach($query as $i) {
- var_dump($i);
- }
- // If you are paranoid, manually disconnect before outputting the response
- DbAccessConnection::disconnectAll();
Copy code
-
namespace PersistenceDbAccess;
- 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 PersistenceDbAccessConnection
- */
- private $connection = null;
- /**
- * PDO Statement
- *
- * @var PDOStatement
- */
- private $stmt = null;
- /**
- * Checked parameter set
- *
- * @var array
- */
- private $checkedParams = array();
- /* *
- * Construct query channel
- *
- * @param PersistenceDbAccessConnection $connection database connection
- */
- public function __construct(Connection $connection)
- {
- $this->connection = $connection;
- }
- /**
- * Precompiled SQL statement
- *
- * @param string $sqlCommand SQL statement
- * @return PersistenceDbAccessQuickQuery
- */
- public function prepare($sqlCommand)
- {
- // Obtain PDO from the connection and execute prepare on the SQL statement to generate PDO Statement
- $this->stmt = $this->connection->getPDO()->prepare($sqlCommand);
- // Modify the PDO Statement mode to associative array data
- $this->stmt->setFetchMode(PDO::FETCH_ASSOC);
- // Return method chain
- return $this;
- }
- /**
- * Execute data query
- *
- * @throws PDOException
- * @return PersistenceDbAccessQuickQuery
- */
- 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));
- }
- // Correspond PHP data type to 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 parameter checks
- return $this;
- }
- /**
- * Get Statement object
- *
- * The returned object can be re-executed with bound parameters, or can be used as an iterator to traverse and obtain data.
- *
- * @return PDOStatement
- */
- public function getStatement()
- {
- if (!$this->stmt) {
- throw new LogicException('SQL statement should be QuickQuery.prepare first Preprocessing');
- }
- return $this->stmt;
- }
- /**
- * Alternative name for the getStatement method
- *
- * Implements the IteratorAggregate interface in the PHP standard library, and external parties can directly use this object as an iterator to traverse
- *. The only difference from getStatment is that this method does not throw LogicException. If
- * prepare and execute are not used beforehand, an empty iterator will be returned.
- *
- * @return Traversable
- */
- public function getIterator()
- {
- try {
- return $this->getStatement() ;
- } catch (LogicException $ex) {
- return new ArrayObject();
- }
- }
- /**
- * Set query parameter check
- *
- * Checked query parameters imported here, if not assigned , then a LogicException will be thrown during query.
- *
- * @param array $params
- * @return PersistenceDbAccessQuickQuery
- */
- 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());
- }
- /**
- * Get the ID of the last inserted result (or sequence)
- *
- * @param string $name
- * @return int
- */
- public function getLastInsertId($name=null)
- {
- return $this->connection->getPDO()->lastInsertId($name);
- }
- }
复制代码
-
namespace PersistenceDbAccess;
- use InvalidArgumentException, BadMethodCallException;
- use PDO, PDOException;
- /**
- * Connection factory, provides global PDO objects, and manages 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 (Database Source Name)
- *
- * @var string
- */
- private $dsn = '';
- /**
- * PDO instance
- *
- * @var PDO
- */
- private $pdo = null;
- /**
- * Username
- *
- * @var string
- * /
- private $username = '';
- /**
- * Password
- *
- * @var string
- */
- private $password = '';
- /**
- * Whether to enable persistent connections
- *
- * @var bool
- */
- private $isPersisten = false;
- /**
- * Whether to enable simulation pre-compilation
- *
- * @var bool
- */
- private $isEmulate = false;
- /**
- * Whether in transaction
- *
- * @var bool
- */
- private $isInTransation = false;
- /**
- * Private constructor, preventing external instantiation using the new operator
- */
- private function __construct(){}
- /* *
- * Production Connector instance (multiple instances)
- *
- * @param string $name
- * @return StuCampusDataModelConnector
- */
- static public function getInstance($name = 'default')
- {
- if (!isset(self::$instances[$name])) {
- // Throws if the accessed instance does not exist An error occurred
- 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 database
- *
- * Add Connector to the instance group
- *
- * @param string $name identification name
- * @param string $driver 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 Whether to persist the connection
- */
- static public function registry($ name, $driver, $dsn, $usr, $pwd, $emulate = false, $persisten = false)
- {
- if (isset(self::$instances[$name])) {
- // If the added instance If the name already exists, an exception will be thrown
- 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 whether PDO has been instantiated, otherwise instantiate PDO first
- $this->pdo = new PDO($this->dsn, $this->username, $ this->password);
- // The error mode is to throw a PDOException exception
- $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- // Enable query caching
- $this- >pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->isEmulate);
- // Enable persistent connections
- $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 translationBegin()
- {
- $this->isInTransation = $this->getPDO()->beginTransaction();
- }
- /**
- * Submit transaction
- */
- public function transationCommit()
- {
- if ($this->isInTransation) {
- $this->getPDO()->commit();
- } else {
- trigger_error('transationBegin should be called before transationCommit') ;
- }
- }
- /**
- * Rollback transaction
- * @return bool
- */
- public function translationRollback()
- {
- 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 $autoRollback Whether to automatically roll back when an exception occurs
- * @throws PDOException
- * @return bool
- */
- public function transationExecute($callback, $autoRollback = true)
- {
- try {
- // Start transaction
- $this->transationBegin();
- // Call callback function
- if (is_callable($callback)) {
- $callback();
- } else {
- throw new InvalidArgumentException('$callback should be a callback function');
- }
- // Commit the transaction
- return $this->transationCommit();
- } catch(PDOException $pex) {
- // If automatic rollback is enabled, Then when catching the PDO exception, roll it back first and then throw it
- if ($autoRollback) {
- $this->transationRollback();
- }
- throw $pex;
- }
- }
- /**
- * Safely disconnect from database
- */
- public function disconnect()
- {
- if ($this->pdo) {
- // Check whether PDO has been instantiated, if so, set it to null
- $this->pdo = null;
- }
- }
- /**
- * Block cloning
- */
- public function __clone()
- {
- trigger_error('Blocked __clone method, Connector is a singleton class');
- }
- }
Copy code
|