PHPackages                             peroks/model-store - 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. peroks/model-store

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

peroks/model-store
==================

Model Store: Permanent data store for models.

1.0.3(11mo ago)037MITPHPPHP &gt;=8.1

Since Jun 11Pushed 11mo ago1 watchersCompare

[ Source](https://github.com/peroks/model-store)[ Packagist](https://packagist.org/packages/peroks/model-store)[ RSS](/packages/peroks-model-store/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (5)Dependencies (3)Versions (6)Used By (0)

Model Store: Permanent data store for models.
=============================================

[](#model-store-permanent-data-store-for-models)

Reason why
----------

[](#reason-why)

The purpose of this package is to store models **permanently**. Currently, **JSON files** and **MySql databases** (mysqli and pdo-mysql) are supported.

The Model Store is an abstraction layer on top of the permanent store. It automatically creates **JSON files** or **database schemas** for you based on your models.

The Model Store provides a simple [interface](src/StoreInterface.php) for reading models from and writing models to the permanents store.

How to use
----------

[](#how-to-use)

### The Store interface

[](#the-store-interface)

You can of course access a database directly, but the recommended way it to create a `Store instance` and use the [StoreInterface](src/StoreInterface.php).

### Connecting to a model store

[](#connecting-to-a-model-store)

In order to connect to a model store, you must create a new **model store instance**. Currently, these model stores are supported:

- `FileStore`: JSON file store
- `MysqlStore`: Native MySql store (mysqli)
- `MysqlJsonStore`: Native MySql (mysqli) store with JSON support
- `PdoStore`: PDO MySql store (pdo-mysqli)
- `PdoJsonStore`: PDO MySql (pdo-mysqli) store with JSON support

The JsonStore classes stores models in MySQL `json` columns with additional columns for indices and constraints.

You can also create your own implementation of the [StoreInterface](src/StoreInterface.php).

#### File store

[](#file-store)

Storing your models in a JSON file is only recommended for **very small** data stores, no more than a few MBs. It's intended for use in **development**and **rapid prototyping**, but not in **production**. For each PHP request the complete JSON file is loaded into memory, and it will consume more and more **ram** and **cpu** as the file grows.

To connect to a JSON file store, just provide the full path and file name to the JSON file which contains your models. If the file does not exist, it will be created.

```
use Peroks\Model\Store\FileStore;
$store = new FileStore( '//.json' );
```

#### PDO MySql store

[](#pdo-mysql-store)

To connect to a PDO MySql store, just provide the [connection info](https://www.php.net/manual/en/mysqli.quickstart.connections.php)for the MySQL database.

All connection properties below are required, except for `port` and `socket`, which are mutually exclusive. If the host is `localhost`, a `socket` is expected. The connection info can be an `array` or an `object`.

```
use Peroks\Model\Store\PdoStore;
$store = new PdoStore( [
    'host'   => 'localhost||',
    'name'   => '',
    'user'   => '',
    'pass'   => '',
    'port'   => '',
    'socket' => '',
] );
```

Alternatively, you can use the `PdoJsonStore` class, which stores the models in MySql `json` columns. Additional columns are only created for primary, index and constraint properties.

#### Native MySql (mysqli) store

[](#native-mysql-mysqli-store)

You can also connect to a MySql database using the native `mysqli` driver if you prefer. Just replace the store class `PdoStore` with `MysqlStore`.

```
use Peroks\Model\Store\MysqlStore;
$store = new MysqlStore( [
    'host'   => 'localhost||',
    'name'   => '',
    'user'   => '',
    'pass'   => '',
    'port'   => '',
    'socket' => '',
] );
```

Alternatively, you can use the `MysqlJsonStore` class, which stores the models in MySql `json` columns. Additional columns are only created for primary, index and constraint properties.

### Creating and Updating database schemas

[](#creating-and-updating-database-schemas)

Before you can start using a database store, you need to build the **database schema** based on your models. Fortunately, you don't need to do this manually. To create (and update) your database schema, call the `build()`method with an array of the model **class names** that you want to store. This will also create a new database if it doesn't already exist.

You should only call the `build()` method when you create a new model store or when your models have changed. Do **not** call `build()` every time you connect to the store. You can use `info( 'ready' )` to check if the db is ready for use or not.

```
use Peroks\Model\Store\MysqlStore;
$store = new MysqlStore( $connection );

if ( ! $store->info( 'ready' ) ) {
    $store->build( [
        MyModelOne::class,
        MyModelTwo::class,
        MyModelThree::class,
    ] );
}
```

If a model contains [sub-models](https://github.com/peroks/model#nested-models), database tables are automatically created for the sub-models. You do not need to include sub-models in the `build()` method. So, if you have a hierarchy of models, you only need to provide your **top-level** models.

Caching
-------

[](#caching)

You can cache query results in memory with the special `Cache` store. The constructor takes another store instance as the only argument. Calls to `has()`, `get()`, `list()` and `filter()` return cached results when available. The cache is cleared every time `set()`, `delete()` or `build()` are called.

```
use Peroks\Model\Store\Cache;
use Peroks\Model\Store\PdoJsonStore;

$store = new Cache( new PdoJsonStore( $connection ) );
$model = $store->get( SomeClass::class, 'someId' );
$model = $store->get( SomeClass::class, 'someId' ); // Cached result.
```

Examples
--------

[](#examples)

The below examples assume that a model store instance has already been created, i.e. like this

```
use Peroks\Model\Store\MysqlStore;
$store = new MysqlStore( [
    'host'   => 'localhost||',
    'name'   => '',
    'user'   => '',
    'pass'   => '',
    'port'   => '',
    'socket' => '',
] );
```

All methods accept the **model class name** as the first argument. The only exception is `set`, since the class name can be derived from the model instance.

#### Check if a model exists in the store

[](#check-if-a-model-exists-in-the-store)

```
$exists = $store->has( MyModelOne::class, 123 );
$exists = $store->has( MyModelOne::class, 'abc' );
```

#### Get a single model by id

[](#get-a-single-model-by-id)

```
$stored_model = $store->get( MyModelOne::class, 123 );
$stored_model = $store->get( MyModelOne::class, 'abc' );
```

#### Get an array of models by their ids

[](#get-an-array-of-models-by-their-ids)

```
$some_models = $store->list( MyModelOne::class, [123, 'abc', 'xyz'] );
$all_models  = $store->list( MyModelOne::class );
```

If no ids are provided, all models of the given class are returned.

#### Get models by their property values

[](#get-models-by-their-property-values)

The `filter` method returns all models of the given **class name** matching pairs of property ids and their values, i.e.

```
$some_artists = $store->filter( Artist::class, [
    'first_name' => 'Tom',
    'last_name'  => 'Waits',
] );

$all_artists = $store->filter( Artist::class );
```

If no property filter is provided, all models of the given class are returned (same as `list()`).

#### Add or update a model in the store

[](#add-or-update-a-model-in-the-store)

```
$model = new Artist( [ 'first_name' => 'Tom', 'last_name' => 'Waits' ] );
$store->set( $model );
```

#### Delete a model from the store

[](#delete-a-model-from-the-store)

```
$store->delete( MyModelOne::class, 123 );
$store->delete( MyModelOne::class, 'abc' );
```

Installing
----------

[](#installing)

You need **composer** to download and install this [package](https://packagist.org/packages/peroks/model-store). Just run `composer require peroks/model-store` in your project.

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance51

Moderate activity, may be stable

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity57

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 ~182 days

Total

5

Last Release

344d ago

Major Versions

0.1.1 → 1.0.02024-12-27

PHP version history (2 changes)0.1.0PHP ^8.1

1.0.0PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/64a1f51e6583f76524ca53eab07eace42fece47d689585ee63cfbe27fb82515e?d=identicon)[peroks](/maintainers/peroks)

---

Top Contributors

[![peroks](https://avatars.githubusercontent.com/u/14331921?v=4)](https://github.com/peroks "peroks (67 commits)")

---

Tags

databasejsonmysqlmysqlipdopdo-mysqlpersistent-storagejsondatabasemysqlpdomysqlipdo\_mysqlpersistent-storage

### Embed Badge

![Health badge](/badges/peroks-model-store/health.svg)

```
[![Health](https://phpackages.com/badges/peroks-model-store/health.svg)](https://phpackages.com/packages/peroks-model-store)
```

###  Alternatives

[sergeytsalkov/meekrodb

The Simple PHP/MySQL Library

341387.0k10](/packages/sergeytsalkov-meekrodb)[ezsql/ezsql

Advance database access library. Make interacting with a database ridiculously easy. An universal interchangeable CRUD system.

86946.7k](/packages/ezsql-ezsql)[jv2222/ezsql

Advance database access library. Make interacting with a database ridiculously easy. An universal interchangeable CRUD system.

87311.3k2](/packages/jv2222-ezsql)[codesvault/howdy-qb

Mysql Query Builder for WordPress

371.2k1](/packages/codesvault-howdy-qb)

PHPackages © 2026

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