phore / unidb
通用数据库访问
dev-main
2022-07-07 19:16 UTC
Requires
- php: >=8.0
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-08 00:09:36 UTC
README
统一数据库访问
特性
- 由于支持PHP8 命名参数,使用简单
基本示例
// Setup table structure and driver $udb = new UniDb( new SqliteDriver(new \PDO("sqlite::memory:")), new Schema( [ "User" => [ "indexes" => ["user_name"] ] ] ) ); // Create the schema (if it does not already exist) echo $udb->createSchema(); // Select the 'User' Table $userTbl = $udb->with("User"); // Insert two entities $userTbl->insert(["user_id"=>"user1", "user_name" => "Bob"]); $userTbl->insert(["user_id"=>"user2", "user_name" => "Alice"]); // Query all datasets with user_name='Bob' OR user_name='Alice' foreach ($userTbl->query(stmt: new OrStmt(["user_id", "=", "Bob"], ["user_id", "=", "Alice"])) as $data) { print_R ($data); }
安装
composer require phore/unidb
定义模式
UniDb 运行查询需要关于模式的基本信息。
查询数据
public UniDb::query( $stmt = null, string $table = null, int $page = null, int $limit = null, string $orderBy = null, string $orderType="ASC", bool $cast = false ) : \Generator
使用生成器访问数据
访问数据的最容易方法是使用生成器
foreach ($odb->query(table: "User") as $user) { print_r ($user); // Will output }
访问完整结果集 / 限制结果 / 分页偏移
$odb->query(table: "User", limit: 10, page: 1); print_r ($odb->result->getResult());
使用对象转换 / 实体
UniDb 可以与对象一起工作,因此使用 phore/hydrator 将结果集转换为对象。通过在参数列表中指定 cast: SomeClass::class
激活此功能。
要使用转换功能,您必须在 composer.json 的要求中添加包
phore/hydrator
foreach ($odb->query(table: "User", cast: User::class) as $obj) { print_r ($obj); // Instance of User class }
查询表中的所有数据
$odb->query(table: "User")
排序数据
语句
为了与 SQL 和 NoSql 数据库兼容,UniDb 使用语句来查询数据。默认情况下,语句将通过 AND 语句链接。
AND 语句
new AndStmt(["name", "=", "Bob"], ["user_name", "=", "bob1"]); // => SELECT ... WHERE name='Bob' AND name='Alice'
OR 语句
new OrStmt(["name", "=", "Bob"], ["name", "=", "Alice"]); // => SELECT ... WHERE name='Bob' OR name='Alice'
嵌套语句
new AndStmt(["name", "=", "Bob"], new OrStmt(["name", "=", "Bob"], ["name", "=", "Alice"])); // => SELECT ... WHERE name='Bob' AND ( name='Bob' OR name='Alice' )
运算符
CRUD 操作
批量更新
UniDb 内置同步方法,用于初始化和更新记录