web-complete / micro-db
MicroDB
1.0.1
2018-01-29 09:00 UTC
Requires
- php: >=7.0.0
Requires (Dev)
- mvkasatkin/mocker: ^1
- phpunit/phpunit: ^6
This package is not auto-updated.
Last update: 2024-09-29 05:08:01 UTC
README
一个无依赖的微型无模式文件数据库库。非常适合小型网站和快速原型设计
安装
composer require web-complete/microDb
使用
创建客户端
$microDb = new MicroDb(__DIR__ . '/storage', 'mydb1');
- 您可以将它切换到运行时内存存储(例如,在测试中)
$microDb->setType('runtime');
获取集合
将集合视为MySQL世界中的表
$usersCollection = $microDb->getCollection('users');
插入项目
$id = $usersCollection->insert(['name' => 'John Smith', 'some_data' => [1,2,3]]);
集合将给项目分配一个新的ID。默认ID字段是"id",但您可以使用任何您想要的
$id = $usersCollection->insert(['name' => 'John Smith', 'some_data' => [1,2,3]], "uid");
批量插入
在一个事务中插入多个项目
$usersCollection->insertBatch( ['name' => 'John Smith 1', 'some_data' => [1,2,3]], ['name' => 'John Smith 2', 'some_data' => [3,4,5]], ['name' => 'John Smith 3', 'some_data' => [5,6,7]], );
更新项目
$filter = function ($item) { return $item['id'] == 2; }; $usersCollection->update($filter, ['name' => 'John Smith 2 updated']);
更新也可以影响多个项目
$filter = function ($item) { return $item['last_visit'] < $newYear; }; $usersCollection->update($filter, ['active' => false]);
删除项目
通过过滤器删除一个或多个项目
$filter = function ($item) { return $item['id'] == 2; }; $usersCollection->delete($filter);
获取多个项目
$filter = function ($item) { return $item['active'] == true; }; $activeUsers = $usersCollection->fetchAll($filter);
或者排序
$filter = function ($item) { return $item['active'] == true; }; $sort = function ($item1, $item2) { return $item1['last_visit'] <=> $item2['last_visit']; }; $activeUsers = $usersCollection->fetchAll($filter, $sort);
并限制20,偏移100
... $activeUsers = $usersCollection->fetchAll($filter, $sort, 20, 100);
获取单个项目
与fetchAll相同的语法(没有限制,偏移),但返回一个项目或null
... $activeUser = $usersCollection->fetchOne($filter, $sort);
按ID查找
$user = $usersCollection->fetchOne(function ($item) { return $item['id'] == 15; });
删除集合
$collection->drop();
运行时存储
运行时存储有两个有用的静态方法,可用于测试
- StorageRuntime::dump() - 返回当前存储阶段
- StorageRuntime::clear() - 清除运行时存储