定制 sorskod/db 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

sorskod/db

Composer 安装命令:

composer require sorskod/db

包简介

PDO wrapper. Extends PDO and PDOStatement with useful methods.

README 文档

README

PDO wrapper extends PDO and PDOStatement classes and add some nice methods as insert/update/delete and so on. Also, there is very useful SQL query builder.

API

Because library extends PDO driver, you can use all of native PDO methods and new additional:

DB - The database class

  • insert - insert object or array as row to database table (optionaly: using prepared statement)
  • update - update existent row in database table (optionaly: using prepared statement)
  • replace - insert or replace (using REPLACE table... syntax)
  • save - save data to table (method determinate does insert or update will be used)
  • delete - delete row(s) in database table
  • count - shortcut for SELECT COUNT(*) statement
  • select - query build object
  • createQuery - create new query builder
  • getColumnsFromTable - all columns from table as array

Statement

  • fetchInto - fetch row into object (optionaly: only from specific table)
  • fetchIntoFromLastRow - fetch another object from last row (based on table name)
  • fetchCollection - fetch collection of objects (custom defined object or stdClass)
  • getColumnValue - value from specific column

Query - Build SQL query object

  • select - statement for SELECT
  • from - statement for FROM
  • where - adding new WHERE statement. Multiple where will be joined by AND
  • whereIn - adding WHERE IN (...) statement
  • whereNotIn - adding WHERE NOT IN (...) statement
  • having - statement for HAVING
  • join - join table syntax
  • groupBy - GROUP BY statement
  • orderBy - ORDER BY statement
  • limit - LIMIT statement
  • getQuery - buld and return query string
  • execute - execute query

See more information about how to use database query builder.

Usage examples

Creating database instance

$db = new database\DB("mysql:host=localhost;dbname=YOUR_DB_NAME", "YOUR_DB_USERNAME", "YOUR_DB_PASSWORD");

Select

Execute query and fetch User object:

class User {}

$user_id = 1;
$sql = "SELECT * FROM users WHERE user_id = ? AND is_active = ?";
$user = $db->executeQuery($sql, array($user_id, 1))
	->fetchInto(new User); // or ->fetchObject("User") as in standard PDO driver

If you need a collection of User objects, you can use fetchCollection method:

$users = $db->executeQuery($sql, array($user_id, 1))
	->fetchCollection(new User); // or ->fetchCollection("User");

More complex, with query builder. You can build 'native' structure of objects. For example, you can fetch collection of objects Post and every Post object may have a property $author which is a instance of User object:

class User
{
    /**
     * Get user's first and last name
     *
     * @return string
     */
    function getName() {
        return $this->first_name . " ". $this->last_name;
    }
}

class Post
{
	/**
	 * @var User
	 */
	public $author;
}

// Library need FETCH_TABLE_NAMES option for mapping class names and table names
$db->setFetchTableNames(1);

$sql = $db->select("p.*, u.*")
	->from("posts p")
	->join("INNER JOIN users u USING(user_id)")
	->where("u.user_id = ?", $user_id)
	->orderBy("p.title");
	
$stmt = $sql->execute();

/* @var Post[] $post_collection  */
$post_collection = array();

// Fetching data into Post object from posts table (p is alias)
while($post = $stmt->fetchInto(new Post, "p")) {

	// fetch User object from users table (u is alias)
	$post->author = $stmt->fetchIntoFromLastRow(new User, "u");

	$post_collection[] = $post;
}

// You can send $post_collection from model to view in your controller, so here is usage in view
foreach($post_collection as $post) {
    echo $post->author->getName();
}

Insert

Library has insert method for easy inserting array or object as row to database table. Note that all other properties or elements that not match column names will be ignored.

$data = array(
	"username" => "User 1234",
	"email" => "user@example.com",
	"mtime" => time()
);
$db->insert("users", $data);

Insert with prepared statement

Third param for insert() method is "unique prepared stmt key". Every insert which have that key will use the same prepared statement.

foreach($data_array as $data) {
	$db->insert("users", $data, "unique_stmt_key");
}

Update

Some examples of update statement

$user_id = 1;
$db->update("users", $data, "user_id = ?", $user_id);
$db->update("users", $data, "user_id = ? AND email = ?", array(1, "user@example.com"));

Saving data

Automatic determination of INSERT or UPDATE. If $data['user_id'] exits it will be UPDATE, otherwise it will be INSERT.

$db->save("users", $data, "user_id"); // user_id is name of PRIMARY column

More examples

// Delete row in table
// some as $db->exec("DELETE FROM users WHERE user_id = 1");
$db->delete("users", "user_id = ?", $user_id);

// Count rows in table
$count = $db->count("users");

/* @var User[] $users Collection of User objects */
$users = $db->executeQuery("SELECT * FROM users")->fetchCollection(new User);

See more examples for Sakila database

sorskod/db 适用场景与选型建议

sorskod/db 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8.33k 次下载、GitHub Stars 达 74, 最近一次更新时间为 2013 年 09 月 15 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「database」 「mysql」 「pdo」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 sorskod/db 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 sorskod/db 我们能提供哪些服务?
定制开发 / 二次开发

基于 sorskod/db 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 8.33k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 78
  • 点击次数: 20
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 74
  • Watchers: 11
  • Forks: 25
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2013-09-15