gamernetwork/yolk-database
最新稳定版本:v1.0
Composer 安装命令:
composer require gamernetwork/yolk-database
包简介
Gamer Network's PHP database abstraction library
README 文档
README
Want to work for Gamer Network? We are hiring!
Yolk Database
A simple database abstraction layer that provides a lightweight wrapper around PDO for ease-of-use. It currently supports MySQL, Postgres and SQLite.
Also included are simple query generators and a class for handling a tree structure within a relational database via modified preorder tree traversal.
Requirements
This library requires only PHP 5.4 or later and the Yolk Contracts package (gamernetwork/yolk-contracts).
Installation
It is installable and autoloadable via Composer as gamernetwork/yolk-database.
Alternatively, download a release or clone this repository, and add the \yolk\database namespace to an autoloader.
License
Yolk Database is open-sourced software licensed under the MIT license
Quick Start
use yolk\database\DSN; use yolk\database\adapters\MySQLConnection; // create a DSN $dsn = DSN::fromString('mysql://localhost/mydb'); // create a connection instance $db = new MySQLConnection($dsn); // get some data $user = $db->getAssoc("SELECT * FROM users WHERE user_id = ?", 123); // update some data $updated = $db->execute( "UPDATE users SET last_seen = :now WHERE id = :id", [ 'id' => 123, 'now' => date('Y-m-d H:i:s'), ] );
DSNs
A DSN is an object that specifies the properties of a database connection.
Common properties are:
type- the type of database to connect to (mysql, postgres or sqlite)host- the host to connect toport- the port number to connect onuser- the user to authenticate aspass- the user's passworddb- the name of the database schema to connect tooptions- an array of driver specific options
DSNs can be created by passing an array of properties to the constructor:
$dsn = new DSN([ 'type' => 'mysql', 'host' => 'localhost', 'db' => 'myapp', ]);
or by calling the static fromString() method with a URI:
$dsn = DSN::fromString('mysql://root:abc123@myapp.db/myapp?charset=utf-8');
ConnectionManager
The ConnectionManager is a service to handle multiple database connections. A client can register a connection or DSN under a specific name and retrieve the connection at a later time.
When a DSN is registered, a suitable connection object is created automatically.
use yolk\database\ConnectionManager; use yolk\database\adapters\SQLiteConnection; // create a ConnectionManager instance $m = new ConnectionManager(); // register a DSN $m->add('mydb1', 'mysql://localhost/mydb'); // register an existing connection $db = new SQLiteConnection('sqlite://var/www/myapp/myapp.db'); $m->add('mydb2', $db); // determine if a connection with the specified name exists $exists = $m->has('mydb1'); // retrieve a previously added connection $db = $m->get('mydb1'); // remove a connection from the manager and return it // NOTE: this does not disconnect the connection $db = $m->remove('mydb1');
Query Method Reference
// Execute a query and return the resulting PDO_Statement $stmt = $db->query($statement, $params = []); // Execute a query and return the number of affected rows $rows = $db->execute($statement, $params = []); // Execute a query and return all matching data as an array of associative arrays of matching rows // Each row array has column names as keys $db->getAll($statement, $params = []); // Execute a query and return all matching data as an associative array, // the first selected column is used as the array key $db->getAssoc($statement, $params = []); // Execute a query and return all matching data as a two-dimensioanl // associative array, the first two selected columns are used as the array keys $db->getAssocMulti($statement, $params = []); // Execute a query and return the first matching row as an associative array $db->getRow($statement, $params = []); // Execute a query and return all values of the first selected column as an array $db->getCol($statement, $params = []); // Execute a query and return the value of the first column in the first array $db->getOne($statement, $params = []);
The above methods accept the following parameters:
$statement: aPDO_Statementinstance or a SQL string$params: an array of parameters to bind to the statement
Query parameters may be bound name:
$user_id = $db->getOne( "SELECT id FROM user WHERE type = :type AND name LIKE :name", [ 'type' => 'NORMAL', 'name' => 'Jim%', ] );
or by position:
$user_id = $db->getOne( "SELECT id FROM user WHERE type = ? AND name LIKE ?", ['NORMAL', 'Jim%'] );
If the query has only a single parameter it may be specified directly and will be automatically converted to a positional parameter:
$user_id = $db->getOne("SELECT id FROM user WHERE login = ?", 'jimbob');
Other Methods
// Returns the ID of the last inserted row or sequence value. $id = $db->insertId($name = ''); // Escape/quote a value for use in a query string $db->quote($value, $type = \PDO::PARAM_STR); // Escape/quote an identifier name (table, column, etc) // Allows reserved words to be used as identifiers. $db->quoteIdentifier('key'); // Execute a raw SQL string and return the number of affected rows. // Primarily used for DDL queries $db->rawExec($sql);
Transactions
// Begin a transaction $db->begin(); // Commit the current transaction $db->commit(); // Rollback the current transaction $db->rollback(); // Determines if a transaction is currently active $db->inTransaction();
Query Generators
OO query generators are available for SELECT, INSERT, UPDATE and DELETE.
An instance of each can be created by calling the corresponding method on the DatabaseConnection.
Select
$db->select() // accepts true (default) or false as argument ->distinct() // comma-separated list or array of column names ->cols('*') // table to select from ->from('table') // append a where clause - column, operator, value // multiple calls add additional clauses ->where('created', '>=', '2016-01-01') // with two arguments, operator is assumed to be '=' ->where('id', 123) // array of columns to group by ->groupBy(['type', 'status']) // second parameter specifies ascending (true) or descending (false) // multiple calls add additional clauses ->orderBy('column', true) // return result as associative array // can also use the other fetch* methods defined by DatabaseConnection ->fetchAssoc();
Insert
$db->insert() // accepts true (default) or false as argument ->ignore() // table to insert to ->into('table') // item to insert as an associative array of column names/values ->item([ 'col1' => 'value1', 'col2' => 'value1', ]) // run the query ->execute();
Update
$db->insert() // accepts true (default) or false as argument ->ignore() // table to insert to ->into('table') // columns to update as an associative array of column names/values ->set([ 'col1' => 'value1', 'col2' => 'value1', ]) // same usage as for SELECT ->where('id', 123) // run the query ->execute();
Delete
$db->delete() // table to insert to ->from('table') // same usage as for SELECT ->where('id', 123) // run the query ->execute();
gamernetwork/yolk-database 适用场景与选型建议
gamernetwork/yolk-database 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8.41k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2014 年 11 月 12 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「framework」 「eurogamer」 「gamer network」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 gamernetwork/yolk-database 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 gamernetwork/yolk-database 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 gamernetwork/yolk-database 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
PHP Framework HLEB2 is the foundation of the web application. Provides ease of development and application performance.
Gamer Network's interface library
Gamer Network's PHP profiling library
Gamer Network's PHP logging component
Gamer Network's PHP framework core
Gamer Network's PHP framework core
统计信息
- 总下载量: 8.41k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 20
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2014-11-12