PHPackages                             mmauksch/json-repositories - 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. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. mmauksch/json-repositories

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

mmauksch/json-repositories
==========================

Basic implementation of the repository pattern that stores its content in serialized json files. Intended use is for testing or prototyping! NOT INTENDED FOR PRODUCTION USE!

1.5.0(7mo ago)0265↓100%MITPHPPHP &gt;=8.1CI passing

Since Aug 3Pushed 7mo agoCompare

[ Source](https://github.com/mmauksch/json-repositories)[ Packagist](https://packagist.org/packages/mmauksch/json-repositories)[ RSS](/packages/mmauksch-json-repositories/feed)WikiDiscussions main Synced today

READMEChangelog (6)Dependencies (7)Versions (14)Used By (0)

JSON File Repository
====================

[](#json-file-repository)

A lightweight PHP library implementing the repository pattern with JSON file persistence. This library provides an easy way to create repositories that store data in JSON files, making it ideal for integration tests, Symfony web tests, and application prototyping.

📋 Overview
----------

[](#-overview)

JSON File Repository offers a simple solution for temporary data persistence without the need for a full database setup. It implements the standard repository pattern, providing familiar interfaces for storing, retrieving, and managing collections of objects.

⚠️ **Note:** This library is intended for testing and prototyping purposes only and is not suitable for production workloads.

🚀 Installation
--------------

[](#-installation)

Install the library via Composer:

```
composer require mmauksch/json-repositories
```

🔧 Usage
-------

[](#-usage)

### Basic Usage

[](#basic-usage)

```
// Set up the repository
$repository = new GenericJsonRepository(
    '/path/to/storage',     // Base storage path
    'entity-directory',     // Subdirectory for this entity type
    SimpleObject::class,    // The entity class
    new Filesystem(),       // Symfony Filesystem component
    $serializer             // Symfony Serializer for JSON conversion
);

// Create and save an object
$object = new SimpleObject();
$object->setId('unique-id');
$object->setName('Object Name');
$repository->saveObject($object, $object->getId());

// Find an object by ID
$foundObject = $repository->findObjectById('unique-id');

// Get all objects
$allObjects = $repository->findAllObjects();

// Delete an object
$repository->deleteObjectById('unique-id');
```

### Extending AbstractRepository

[](#extending-abstractrepository)

Instead of using GenericJsonRepository as an instance, you can also extend the AbstractJsonRepository class to create your own repository implementation:

```
class UserRepository extends AbstractJsonRepository
{
    public function __construct(string $jsonDbBaseDir, Filesystem $filesystem, SerializerInterface $serializer)
    {
        parent::__construct($jsonDbBaseDir, 'users', User::class, $filesystem, $serializer);
    }

    // Add custom methods specific to your domain
    public function findByUsername(string $username): ?User
    {
        return $this->findMatchingFilter(function(User $user) use ($username) {
            return $user->getUsername() === $username;
        })[0] ?? null;
    }
}
```

### Using Traits Selectively

[](#using-traits-selectively)

You can also build your own repository implementation by selectively importing the traits that provide specific functionality:

```
class CustomRepository implements BasicJsonRepository
{
    // Only include the basic CRUD operations
    use BasicJsonRepositoryTrait;

    // You can add the other traits as needed:
    // use FilterableJsonRepositoryTrait;
    // use SortableJsonRepositoryTrait;

    private string $basePath;
    protected string $targetClass;

    public function __construct(string $basePath, string $targetClass, Filesystem $filesystem, SerializerInterface $serializer)
    {
        $this->basePath = $basePath;
        $this->targetClass = $targetClass;
        $this->filesystem = $filesystem;
        $this->serializer = $serializer;
    }

    protected function objectStoreDirectory(): string
    {
        return $this->basePath;
    }
}
```

### Using Filters

[](#using-filters)

```
// Find objects matching a filter using a closure
$filteredObjects = $repository->findMatchingFilter(function (SimpleObject $object) {
    return $object->getName() === 'Object Name';
});

// Or implement a Filter class
class NameFilter implements Filter {
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

    public function __invoke(object $object): bool {
        return $object->getName() === $this->name;
    }
}

$filteredObjects = $repository->findMatchingFilter(new NameFilter('Object Name'));
```

### Using Sorters

[](#using-sorters)

```
// Sort objects using a closure
$sortedObjects = $repository->findAllObjectSorted(function (SimpleObject $a, SimpleObject $b) {
    return strcmp($a->getName(), $b->getName());
});

// Or implement a Sorter class
class NameSorter implements Sorter {
    public function __invoke(object $a, object $b): int {
        return strcmp($a->getName(), $b->getName());
    }
}

$sortedObjects = $repository->findAllObjectSorted(new NameSorter());
```

### Using with Symfony Tests

[](#using-with-symfony-tests)

```
// In your test class
protected static string $repodir = 'entities';
protected static ?string $temppath = null;
protected static Filesystem $filesystem;
private GenericJsonRepository $repository;

public static function setUpBeforeClass(): void
{
    self::$filesystem = new Filesystem();
    self::$temppath = sys_get_temp_dir().'/'.'jsondb_'.uniqid();
    self::$filesystem->mkdir(self::$temppath);
}

public static function tearDownAfterClass(): void
{
    if(is_dir(self::$temppath))
        self::$filesystem->remove(self::$temppath);
    self::$temppath = null;
}

protected function setUp(): void
{
    $repositoryDir = Path::join(self::$temppath, static::$repodir);
    if(is_dir($repositoryDir))
        self::$filesystem->remove($repositoryDir);

    // Create a clean repository for each test
    $this->repository = new GenericJsonRepository(
        self::$temppath,
        self::$repodir,
        Entity::class,
        self::$filesystem,
        $this->getSerializer()
    );
}

private function getSerializer(): SerializerInterface
{
    return new Serializer(
        [new ObjectNormalizer(
            null, null, null,
            new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()])
        ), new ArrayDenormalizer()],
        [new JsonEncoder()]
    );
}
```

### For Application Prototyping

[](#for-application-prototyping)

```
// In your service configuration (Symfony)
public function configureServices(ContainerBuilder $container)
{
    // ...

    // Setup serializer if not already configured
    $container->register('app.json_serializer', Serializer::class)
        ->setArguments([
            [new Reference('serializer.normalizer.object'), new Reference('serializer.normalizer.array')],
            [new Reference('serializer.encoder.json')]
        ]);

    // Register the repository
    $container->register(EntityRepositoryInterface::class)
        ->setClass(GenericJsonRepository::class)
        ->setArguments([
            '%kernel.project_dir%/var/storage',  // Base path
            'entities',                         // Entity directory
            Entity::class,                      // Entity class
            new Reference('filesystem'),        // Symfony Filesystem
            new Reference('app.json_serializer') // Serializer
        ]);
}
```

You can also simply let the dependency injection container provide the filesystem and serializer. In Symfony YAML configuration:

```
# config/services.yaml
services:
    # User repository with autowiring
    App\Repository\UserRepository:
        class: GenericJsonRepository
        arguments:
            $jsonDbBaseDir: '%kernel.project_dir%/var/storage'
            $dirName: 'users'
            $targetClass: 'App\Entity\User'
        # The filesystem and serializer will be automatically injected
        autowire: true
```

🔄 Key Features
--------------

[](#-key-features)

- **Simple Repository Pattern Implementation** - Follows standard repository interfaces
- **JSON File Persistence** - Stores entities as JSON files without database setup
- **Flexible Storage Location** - Configure where your JSON files are stored
- **Advanced Filtering** - Filter entities using both Filter objects and closures
- **Custom Sorting** - Sort entities using Sorter objects or custom comparison closures
- **Type Safety** - Repositories are typed to specific entity classes
- **Symfony Integration** - Works with Symfony Filesystem and Serializer components

💡 Best Practices
----------------

[](#-best-practices)

- Use a dedicated directory for test storage that is cleared between test runs
- For integration tests, create fresh repositories in your test setup
- Implement proper cleanup in tearDown() methods or use a test framework's isolation features
- Consider using memory-only repositories for very simple tests

🧪 When to Use
-------------

[](#-when-to-use)

- ✅ Writing integration tests
- ✅ Developing Symfony web tests
- ✅ Prototyping applications or features
- ✅ Demos and proof of concepts
- ❌ Production applications
- ❌ High-performance requirements
- ❌ Applications with complex database requirements

📄 License
---------

[](#-license)

This project is licensed under the MIT License - see the LICENSE.md file for details.

🤝 Contributing
--------------

[](#-contributing)

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.

###  Health Score

37

—

LowBetter than 84% of packages

Maintenance64

Regular maintenance activity

Popularity14

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 96.9% 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 ~2 days

Total

7

Last Release

219d ago

PHP version history (2 changes)1.0.0PHP &gt;=8.0

1.1.0PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/a077b1a80558bef2c388eb7bbf6259949d4198e069ca61820e6aed06d4110a7c?d=identicon)[mmauksch](/maintainers/mmauksch)

---

Top Contributors

[![mmauksch](https://avatars.githubusercontent.com/u/87762329?v=4)](https://github.com/mmauksch "mmauksch (31 commits)")[![devkatz](https://avatars.githubusercontent.com/u/148793601?v=4)](https://github.com/devkatz "devkatz (1 commits)")

---

Tags

jsonrepositoryprototyping

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mmauksch-json-repositories/health.svg)

```
[![Health](https://phpackages.com/badges/mmauksch-json-repositories/health.svg)](https://phpackages.com/packages/mmauksch-json-repositories)
```

###  Alternatives

[justinrainbow/json-schema

A library to validate a json schema.

3.6k311.5M540](/packages/justinrainbow-json-schema)[mtdowling/jmespath.php

Declaratively specify how to extract elements from a JSON document

2.0k463.5M120](/packages/mtdowling-jmespathphp)[jms/serializer

Library for (de-)serializing data of any complexity; supports XML, and JSON.

2.3k133.8M798](/packages/jms-serializer)[jms/serializer-bundle

Allows you to easily serialize, and deserialize data of any complexity

1.8k88.3M588](/packages/jms-serializer-bundle)[colinodell/json5

UTF-8 compatible JSON5 parser for PHP

30421.2M39](/packages/colinodell-json5)[clue/ndjson-react

Streaming newline-delimited JSON (NDJSON) parser and encoder for ReactPHP.

15063.4M13](/packages/clue-ndjson-react)

PHPackages © 2026

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