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-11-10 05:45:51 UTC
README
Tiny schemaless file DB library with no dependencies. Most suitable for small sites and fast prototyping
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
$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:
$id = $usersCollection->insert(['name' => 'John Smith', 'some_data' => [1,2,3]], "uid");
batch insert
Insert many items in one transaction
$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:
$filter = function ($item) { return $item['last_visit'] < $newYear; }; $usersCollection->update($filter, ['active' => false]);
delete item
delete one or more items by filter
$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:
$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:
... $activeUsers = $usersCollection->fetchAll($filter, $sort, 20, 100);
fetch one item
The same syntax as fetchAll (without limit, offset), but returns one item or null
... $activeUser = $usersCollection->fetchOne($filter, $sort);
Find by id:
$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