PHP code example of mmauksch / json-repositories

1. Go to this page and download the library: Download mmauksch/json-repositories library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mmauksch / json-repositories example snippets


// 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');

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;
    }
}

class CustomRepository implements BasicJsonRepository 
{
    // Only ts 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;
    }
}

// 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'));

// 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());

// 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()]
    );
}

// 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
        ]);
}