PHP code example of milpa / data

1. Go to this page and download the library: Download milpa/data 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/ */

    

milpa / data example snippets


use Milpa\Data\EntityInterface;
use Milpa\Data\FileRepository;

final readonly class Article implements EntityInterface
{
    public function __construct(
        public int|string|null $id,
        public string $title,
        public string $status,
    ) {
    }

    public function id(): int|string|null
    {
        return $this->id;
    }

    public function toArray(): array
    {
        return ['id' => $this->id, 'title' => $this->title, 'status' => $this->status];
    }

    public static function fromArray(array $row): static
    {
        return new self($row['id'] ?? null, $row['title'], $row['status']);
    }
}

$repo = new FileRepository('/var/data/articles.json', Article::class);

// Save: no id yet, so the repository assigns one and hands it back.
$id = $repo->save(new Article(null, 'Hello Milpa', 'draft'));

// A fresh instance, pointed at the same file, reads back exactly what was written —
// no shared state, no cache, just the file itself.
$reread = new FileRepository('/var/data/articles.json', Article::class);
$found = $reread->find($id);
printf("%s (%s)\n", $found->title, $found->status);
// Hello Milpa (draft)

$reread->query(['status' => 'draft']); // [Article{id: 1, title: 'Hello Milpa', status: 'draft'}]

use Milpa\Data\RepositoryFactory;

$repo = RepositoryFactory::fromConfig([
    'driver' => 'file',
    'path'   => '/var/data/articles.json',
], Article::class);

// config/app.php
return [
    'storage' => [
        'driver' => 'sqlite',                        // ← the one line
        'path'   => __DIR__ . '/../var/data/app.db',
    ],
];

// in a plugin's boot()
$storage = $this->container->get(Config::class)->get('storage', [
    'driver' => 'file',
    'path'   => $root . '/var/articles.json',       // zero-config default
]);
$this->container->registerService(
    Article::class . 'Repository',
    RepositoryFactory::fromConfig($storage, Article::class),
);