PHPackages                             maer/file-db - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. maer/file-db

ActiveLibrary[Database &amp; ORM](/categories/database)

maer/file-db
============

Extendable flat file database written in PHP

0.3.2(8y ago)472MITPHPPHP &gt;=7.0

Since Feb 5Pushed 3y ago1 watchersCompare

[ Source](https://github.com/magnus-eriksson/file-db)[ Packagist](https://packagist.org/packages/maer/file-db)[ RSS](/packages/maer-file-db/feed)WikiDiscussions develop Synced 2mo ago

READMEChangelogDependencies (2)Versions (11)Used By (0)

File based database written in PHP
==================================

[](#file-based-database-written-in-php)

[![Build Status](https://camo.githubusercontent.com/3937ac53c1c29c1e9786a229d7eca6fc0f83b7c5150f7b6a99de5b1990c2c16c/68747470733a2f2f6170692e7472617669732d63692e6f72672f6d61676e75732d6572696b73736f6e2f66696c652d64622e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/magnus-eriksson/file-db)

This library makes it possible to store and retrieve data sets in your application without the need of databases. The data is stored in your file system as json files and can be retrieved through an easy to use query builder.

> This is not meant to replace databases in high performance applications, but rather a convenient way of storing, filtering and retrieving smaller data sets.

- [Install](#install)
- [Instantiate](#instantiate)
- [Storage drivers](#storage-drivers)
    - [File system](#file-system)
    - [Memory](#memory)
- [Query builder](#query-builder)
    - [Tables](#tables)
    - [Insert](#insert)
        - [Batch insert](#batch-insert)
    - [Get data](#get-data)
        - [Get all items](#get-all-items)
        - [Get first item](#get-first-item)
        - [Find](#find)
        - [Where](#where)
        - [Order by](#order-by)
        - [Limit](#limit)
        - [Offset](#offset)
        - [As Object](#as-object)
    - [Update](#update)
    - [Replace](#replace)
    - [Delete](#delete)
    - [Truncate](#truncate)

Install
-------

[](#install)

Using composer:

```
composer require maer/file-db

```

Instantiate
-----------

[](#instantiate)

To create an instance, you need to pass which [storage driver](#storage-drivers) you want to use:

```
$driver = new SomeStorageDriver();

$db = new Maer\FileDB\FileDB($driver);
```

Storage drivers
---------------

[](#storage-drivers)

### File system

[](#file-system)

File system stores the data, as suggested, on the file system. This is the driver you need to use if you want your data to be persistent between requests:

```
$driver = new Maer\FileDB\Storage\FileSystem(
    '/absolute-path/to/your/storage/folder'
);
```

The storage folder must be writable.

> **Important:** Since the data will be saved in json-format, this folder should also be placed *outside* of the document root, or people will be able to access the data directly.

### Memory

[](#memory)

The memory driver only stores the data in memory for the current request and will *not* be persistent between requests. This driver is primarily meant to be used as a mock driver for tests.

```
$driver = new Maer\FileDB\Storage\Memory();
```

Query builder
-------------

[](#query-builder)

### Tables

[](#tables)

You can have as many tables (or rather collections) as you want. Each table will be stored in it's own file.

When you get a table from the File DB, you're actually getting a new instance of the [Query builder](#query-builder) (`Maer\FileDB\QueryBuilder`) so you can start building your query:

```
$query = $db->table('people');

// or shorthand

$query = $db->people;
```

If that table doesn't exist, it will automatically be created when you store data in it for the first time.

### Insert

[](#insert)

Inserting data is simple. Simply pass the data as an associative array:

```
$id = $db->people->insert([
    'first_name'   => 'Chuck',
    'last_name'    => 'Norris',
    'masters'      => 'everything',
]);
```

If the insert was successful, this will return the new ID. If the insert failed, `null` will be returned.

> **Note on ID's:** When you add an item and no ID is passed (passed as `id`), an unique and random 16 char hex string will be generated.

> If you *do* pass an ID that already exists in that table, the query will fail and return `null`.

#### Batch insert

[](#batch-insert)

If you want to insert multiple items at once, you can use `batchInsert(array $data)`

```
$ids = $db->people->batchInsert([
    [
        'first_name' => 'Chuck',
        'last_name'  => 'Norris',
    ],
    [
        'first_name' => 'Jackie',
        'last_name'  => 'Chan',
    ]
]);
```

This method returns all the generated ID's.

### Get data

[](#get-data)

Most of the below items will return a multi dimensional array with the matching items.

#### Get all items

[](#get-all-items)

```
$rows = $db->people->get();
```

#### Get first item

[](#get-first-item)

Return the first matched item.

```
$row = $db->people->first();
```

#### Find

[](#find)

Get first item that matches a condition.

```
// Find by ID (default)
$row = $db->people->find('123');

// Find by some other column
$row = $db->people->find('Chuck', 'first_name');
```

##### Where

[](#where)

Usually, you only want to return some specific items which match some type of criteria. You can do this by adding some "where" conditions to your query:

```
$rows = $db->people->where('masters', 'everything')->get();
```

The above will match all items that has `everything` as the value for the column `masters`. This equals: `where('masters', '=', 'everything')`.

##### Operators

[](#operators)

There are many more operators you can use to narrow down the result.

The below operators are used like this: `where($column, $operator, $value)`

```
=           Equal to (Loose type comparison)
!=          Not equal to (Loose type comparison)
===         Equal to (Strict type comparison)
!==         Not equal to (Strict type comparison)
<           Lower than
>           Higher than
=          Higher or equal to
*           Contains
=*          Starts with
*=          Ends with
in          Exists in list
!in         Not exists in list
regex       Match using regular expressions.
func        Match using a custom callback (closure as the third argument)
array_has   Exists in array  (if the value is an array)
!array_has  Not exists in array (if the value is an array)
has_col     The column exist
!has_col    The column does not exist

```

You can add as many where conditions as you like to the same query. To make it easier, you can chain them:

```
$result = $db->people->where('col1', '=', 'some value')
    ->where('col2', '!=', 'some other value')
    ...
    ->get();
```

#### Order by

[](#order-by)

To sort the result in a specific way, you can use `orderBy($column, $order = 'asc')`.

```
// Ascending order:
$results = $db->people->orderBy('first_name');

// Descending order:
$results = $db->people->orderBy('first_name', 'desc');
```

#### Limit

[](#limit)

You can limit the amount of items returned.

```
// Only get the 2 first matches
$results = $db->people->limit(2)->get();
```

#### Offset

[](#offset)

If you need to add an offset (for using with pagination, for example), you can use `offset($offset)`:

```
// Get all results from the second match and forward.
$results = $db->people->offset(2)->get();
```

#### As Object

[](#as-object)

By default, all items will be returned as associative arrays. If you rather have them returned as objects, you can use the method `asObj($class = 'stdClass')`:

```
// Default, converts the item to a StdClass
$item = $db->people->asObj()->first();

// Using your own entity class
$item => $db->people->asObj('Namespace\PersonClass')->find();
```

When passing a custom class, the item will be passed to the class in the constructor (as an array), so it's up to your custom class to populate it's properties accordingly.

### Update

[](#update)

To update an item, use `update(array $data)`:

```
$affected = $db->people
    ->where('first_name', 'Chuck')
    ->where('last_name', 'Norris')
    ->update([
        'middle_name' => 'The king',
    ]);
```

This method returns the number of affected items.

> Don't forget the `where`-clause or you will update *all* items.

### Replace

[](#replace)

The difference between this method and `update()` is that this replaces the complete item, except from the ID. Example:

```
$id = $db->people->insert([
    'foo'     => 'Lorem',
    'bar'     => 'Ipsum',
]);

$affected = $db->people
    ->where('id', $id)
    ->replace([
        'foo_bar' => 'Lorem Ipsum',
    ]);

$item = $db->people->find($id);
// Returns:
// [
//     'id'      => 1234,
//     'foo_bar' => 'Lorem Ipsum',
// ]
```

This method returns the number of affected items.

> Don't forget the `where`-clause or you will replace *all* items.

### Delete

[](#delete)

Delete items

```
$affected = $db->people
    ->where('first_name', 'Chuck')
    ->delete();
```

This method returns the number of affected items.

> Don't forget the `where`-clause or you will delete *all* items.

### Truncate

[](#truncate)

Truncate a table. (Deletes all items)

```
$success = $db->people->truncate();
```

This method returns a boolean. `true` on success and `false` on error.

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~53 days

Recently: every ~78 days

Total

7

Last Release

3066d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1ada6171adca1bf89432dd54fff188ef3d890a71734278bd06b54487f45b5695?d=identicon)[maer](/maintainers/maer)

---

Top Contributors

[![magnus-eriksson](https://avatars.githubusercontent.com/u/3640297?v=4)](https://github.com/magnus-eriksson "magnus-eriksson (13 commits)")

---

Tags

flat-file-dbphp

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/maer-file-db/health.svg)

```
[![Health](https://phpackages.com/badges/maer-file-db/health.svg)](https://phpackages.com/packages/maer-file-db)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M546](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
