MicroDB
, (*1)
Tiny schemaless file DB library with no dependencies. Most suitable for small sites and fast prototyping, (*2)
Installation
composer require web-complete/microDb
Usage
create client
$microDb = new MicroDb(__DIR__ . '/storage', 'mydb1');
- you can switch it to runtime in-memory storage (for example, in tests)
$microDb->setType('runtime');
get collection
Think about collection as a table in mysql-world, (*3)
$usersCollection = $microDb->getCollection('users');
insert item
$id = $usersCollection->insert(['name' => 'John Smith', 'some_data' => [1,2,3]]);
Collection will assign the item a new id. Default id field is "id", but you can use any you wish instead:, (*4)
$id = $usersCollection->insert(['name' => 'John Smith', 'some_data' => [1,2,3]], "uid");
batch insert
Insert many items in one transaction, (*5)
$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]],
);
update item
$filter = function ($item) {
return $item['id'] == 2;
};
$usersCollection->update($filter, ['name' => 'John Smith 2 updated']);
update can affect many items as well:, (*6)
$filter = function ($item) {
return $item['last_visit'] < $newYear;
};
$usersCollection->update($filter, ['active' => false]);
delete item
delete one or more items by filter, (*7)
$filter = function ($item) {
return $item['id'] == 2;
};
$usersCollection->delete($filter);
fetch many items
$filter = function ($item) {
return $item['active'] == true;
};
$activeUsers = $usersCollection->fetchAll($filter);
or with sorting:, (*8)
$filter = function ($item) {
return $item['active'] == true;
};
$sort = function ($item1, $item2) {
return $item1['last_visit'] <=> $item2['last_visit'];
};
$activeUsers = $usersCollection->fetchAll($filter, $sort);
and limit 20, offset 100:, (*9)
...
$activeUsers = $usersCollection->fetchAll($filter, $sort, 20, 100);
fetch one item
The same syntax as fetchAll (without limit, offset), but returns one item or null, (*10)
...
$activeUser = $usersCollection->fetchOne($filter, $sort);
Find by id:, (*11)
$user = $usersCollection->fetchOne(function ($item) {
return $item['id'] == 15;
});
drop collection
$collection->drop();
runtime storage
Runtime storage has 2 useful static methods to use in testing:
- StorageRuntime::dump() - returns current storage stage
- StorageRuntime::clear() - clears runtime storage, (*12)