SleekDB - A NoSQL Database made using PHP

SleekDB is a simple NoSQL database that store data in plain JSON files.

Intentionally SleekDB is not designed for heavy-load IO operations, it is designed to have a simple solution where we need a database for managing few gigabytes of data.

SleekDB works great as the database engine for most low to medium traffic websites.

Any site that gets fewer than 50k to 100K hits/day should work fine with SleekDB.

Features

Light-weight, only ~30Kb.
Stores data in plain-text utilizing JSON format,
no binary conversion needed to store or fetch the data.
Schema free data storage.
SleekDB does not require any schema
meaning you can insert any types of data you want.
Query on nested properties.
Supports filter and conditions on nested properties
of the JSON documents!
Dependency free, only requires PHP to run.
Supports PHP 5.5+, PHP 7+
Requires no third-party plugins or softwares.
Default caching layer.
SleekDB will serve data from cache by default
and regenerate cache each time it creates an object!
Filter, sort, skip, limit and search.
Use multiple conditional comparisons, text search,
sorting on multiple properties and nested properties.
Runs every where.
Runs perfectly on shared-servers or VPS too.
Easy to learn and implement.
SleekDB provides a very simple elegant
API to handle all of your data.
Easily import/expert or backup data.

How to install and use SleekDB?

To use SleekDB make sure that you have PHP up and running in your system, and SleekDB has write permission.

Using SleekDB in a PHP project

Composer Installation

To install SleekDB using composer, open a terminal and run this:

composer require rakibtg/sleekdb

Now create the SleekDB object.

$sdb = new \SleekDB\SleekDB( "items" );

Find SleekDB on packagist.

Install Manually (Without Composer)

  1. Download the latest version and extract the ZIP file inside your project directory.
  2. Import the SleekDB.php file where you want to use SleekDB. Example:
    require_once "../SleekDB/SleekDB.php";
    
  3. Create a new SleekDB object. You will need to provide a store name while creating the object. Example:
    $sdb = new \SleekDB\SleekDB( "items" );
    
    Note that here "items" is a store name, it's like the table name for MySQL. This object is only responsible for the "items" store. We could create more than one object for each stores.
  4. Time to test! Let's insert some data.
    // An array that we want to insert.
    $items = [
      [
        "title" => "Google Pixel 2",
        "about" => "The unlocked Pixel 2 provides..."  
      ],
      [
        "title" => "Google Pixel XL",
        "about" => "The unlocked biggest Pixel 2..."  
      ]
    ];
    $results = $sdb->insertMany( $items ); 
    
    The results variable would contain all the inserted data and with the _id property.

Using SleekDB Independently

SleekDB would have a server that can handle all the data and returns them, works separately and independently. This feature is not implemented yet.

Configurations

The configuration file "config.php" is located at the root directory of SleekDB. It has has an array called $config with few properties. Lets talk about them.

1. storeLocation

You can specify where to store data in the storeLocation property of the $config array. Example:

$config[ 'storeLocation' ] = '/home/user/datastore/';

2. enableAutoCache

In the $config array the enableAutoCache is set to true by default!

This tells SleekDB to cache the data of an unique database query and later re-use the cache for the same query.

To keep the cached data synced with new data, SleekDB will delete all cache when we insert any new data to a store.

To disable it update the value of enableAutoCache to false in the $config array.

Note that you can manually manage cache data with methods that SleekDB provides. Available caching method's are: makeCache(), useCache(), deleteCache() and deleteAllCache()

3. timeOut

Set timeout value, default value is 120 second.

Understanding Store

The "store" contains all your data as JSON files, we call them data object. While using SleekDB you don't have to manage a store.

When you create a new SleekDB object you need to provide a store name, if the store is not exists then SleekDB will create the store for you.

At this moment you can not edit/delete a store, but you can do it manually using the File Browser of your OS or using the terminal.

The Database Object

To work with a store we will need to create a new SleekDB object with that store name.

Throughout this API documentation we are going to use a store called "users". So lets create the database object.

$usersDB = new SleekDB( 'users' );

Insert Data

To insert data first you make a PHP array, and simply insert that array.

Insert A Single Data Object

Using the insert() method we will insert a new data object. Example:

// Prepare a PHP array to insert.
$user = [
  'name' => 'Kazi Hasan',
  'products' => [
    'totalSaved' => 19,
    'totalBought' => 27
  ],
  'location' => [
    'town' => 'Nagar',
    'city' => 'Dhaka',
    'country' => 'Bangladesh'
  ]
];
// Insert the data.
$user = $usersDB->insert( $user );
Here, the insert() method will return the inserted object with the _id property which is generated by SleekDB.

Insert Multiple Data Object

Using the insertMany() method you can insert more than one data object at a time, example:
// Prepare users data.
$users = [
  [ 
    'name' => 'Russell Newman',
    'products' => [
      'totalSaved' => 5,
      'totalBought' => 3
    ],
    'location' => [
      'town' => 'Andreas Ave',
      'city' => 'Maasdriel',
      'country' => 'England'
    ]
  ],
  [ 
    'name' => 'Willard Bowman',
    'products' => [
      'totalSaved' => 0,
      'totalBought' => 0
    ],
  ],
  [
    'name' => 'Tommy Mendoza',
    'products' => [
      'totalSaved' => 172,
      'totalBought' => 54
    ],
  ],
  [
    'name' => 'Joshua Edwards',
    'phone' => '(382)-450-8197'
  ]
];
// Insert all data.
$usersDB->insertMany( $users );
The insertMany() method will return the inserted object with the _id property which is generated by SleekDB.

Fetch Data

To get data from the store we use the fetch() method. Example:

$usersDB->fetch();

The above command would query into the "users" store to fetch all the data.

Apply Filters and Conditions

To filter data we use the where() method.

The where() method takes three arguments, those are:

where( $fieldName, $condition, $value );

  1. $fieldName

    The filed name argument is the property that we want to check in our data object.

    As our data object is basically a JSON document so it could have nested properties.

    To target nested properties we use a single dot between the property/field name.

    Example: From our above users object if we want to target the "country" property of a user, then we would pass location.country in this argument, because "location" is the parent property of the "country" property in our data object.

  2. $condition

    To apply the comparison filters we use this argument.

    Allowed comparisonal conditions are:

    • = Match equal against data.
    • != Match not equal against data.
    • > Match greater than against data.
    • >= Match greater equal against data.
    • < Match less than against data.
    • <= Match less equal against data.

  3. $value

    Data to be used as against the property value of the JSON documents.

Example of using where() to filter data
To only get the user whose country is equal to "England" we would query like this:

$user = $usersDB->where( 'name', '=', 'Joshua Edwards' )->fetch();

You can use multiple where() conditions. Example:

$user = $usersDB->where( 'products.totalSaved', '>', 10 )
          ->where( 'products.totalBought', '>', 20 )
        ->fetch();

Edit Data

To edit a data object we would use the update() method.

The update method takes only one argument.

update( $updateable );

Lets update the "totalBought" value of a user whose name is "Joshua Edwards"

$updateable = [
  'products' => [
    'totalBought' => 1
  ]
];
$usersDB->where( 'name', '=', 'Joshua Edwards' )->update( $updateable );

You can use more than one where condition if required.

Delete Data

To delete a data object we would use the delete() method. Example:

Lets delete the user whose name is "Joshua Edwards"

$usersDB->where( 'name', '=', 'Joshua Edwards' )->delete();

You can use more than one where condition if required.

Skip and Limit Data

To skip a set of record we will use the skip() method. Example:

// Skip the first 5 users.
$users = $usersDB->skip( 5 )->fetch();

To limit a set of record we will use the limit() method. Example:

// Fetch only 5 users.
$users = $usersDB->limit( 5 )->fetch();

Query Offset

To obtain the query offset feature we can chain skip() and limit() into one query. Example:

$users = $usersDB
          ->where( 'age', '>=', 18 )
          ->skip( 15 )
          ->limit( 5 )
        ->fetch();

The above query will skip first 15 records and will limit to next 5 records of data objects. This way we can also perform paginate.

Sort Data

To sort data objects we would use the orderBy() method.

The orderBy method takes two argument,

orderBy( $order, $orderBy );

  1. $order argument receives the order direction, "asc" or "desc".
  2. $orderBy argument receives the property name on which we want to sort. Default is _id property.

Lets sort the data based on total items bought by the user.

$users = $usersDB
          ->orderBy( 'desc', 'products.totalBought' )
          ->limit( 20 )
        ->fetch();

Search Data

We can search data using the search() method. It utilizes the similar_text() function and works better on medium length string.

The search method takes two argument,

search( $field, $keyword );

  1. $field argument receives the property name on which we want to perform the search.
  2. $keyword is the search keyword.

Lets search for users who lives in Canada.

$users = $usersDB
          ->search( 'location.country', 'Canada' )
        ->fetch();

To ensure proper search result we can search more than one property at a time. Example,

$users = $usersDB
          ->search( 'bio', 'I Love Canada' )
          ->search( 'location.country', 'Canada' )
          ->where( 'active', '=', 1 )
        ->fetch();

Use Cache

The useCache() method would return the data from the cache storage, if cache dosent exists then it would fetch the result then creates the cache for later use and return the data. Example,

$user = $usersDB
          ->where( 'active', '=', 1 )
          ->where( 'location.country', '=' 'United States' )
          ->search( 'bio', 'PHP developer' )
          ->search( 'bio', 'SleekDB' )
          ->orderBy( 'desc', 'rank' )
          ->limit( 20 )
          ->useCache() // Use the cache data.
        ->fetch();

Re-generate Cache

To re-generate the cache for a query we would use the makeCache() method.

Its more like the useCache() method but the only difference is that instead of looking for existing cache data it would replace the old cache by generating a new cache from fresh data fetched. Example,

$user = $usersDB
          ->search( 'bio', 'SleekDB' )
          ->orderBy( 'desc', 'rank' )
          ->skip( 80 )
          ->limit( 20 )
          ->makeCache() // Re-generate the cache data.
        ->fetch();

Delete Cache

To delete the cache of a query we would use the deleteCache() method. Example,

$user = $usersDB
          ->search( 'bio', 'SleekDB' )
          ->orderBy( 'desc', 'rank' )
          ->skip( 80 )
          ->limit( 20 )
        ->deleteCache();

Note that if you need to get the data please add the fetch() method.

Delete All Cache

To delete all cache use the deleteAllCache() method. Example,

$usersDB->deleteAllCache();
Tweet us your thoughts.
Or, direct message me on twitter @rakibtg
Or, send an email at rakibtg@gmail.com

I would love to see how you are using the database, if you have implemented something or how it is working for you.
What changes will make you more interested.
If you want to submit a bug feel free to create a new issue.

SleekDB is a open-source NoSQL database licensed under the MIT License. Source code on GitHub

Website designed by @rakibtg • This website is also open-source!

© Copyright - SleekDB • By @rakibtg