Skip to content

Instantly share code, notes, and snippets.

@4lb0
Created September 21, 2021 22:25
Show Gist options
  • Save 4lb0/69a002962cdec07d732a92f26304ce56 to your computer and use it in GitHub Desktop.
Save 4lb0/69a002962cdec07d732a92f26304ce56 to your computer and use it in GitHub Desktop.
Doclite ActiveRecord
<?php
declare(strict_types=1);
use Gebler\Doclite\Database;
use FernetDb\Record;
// set up
$db = new FileDatabase($_ENV['DB_PATH']);
Record::setUp($db);
// Entity class
class User extends Record
{
public string $email;
public string $name;
}
// Create
$user = User::new();
$user->email = "test@example.com";
$user->name = "John Doe";
$user->save();
// Find
$user = User::find(['email' => 'test@example.com'])->current();
// Active Record class, the entity should extend this
class Record
{
public ?string $__id;
static private Database $db;
static public function setUp(Database $db)
{
static::$db = $db;
}
static protected function getCollection()
{
$name = strtolower(str_replace('\\','_', static::class));
return static::$db->collection($name);
}
static public function new()
{
return static::getCollection()->get(null, static::class);
}
static public function find(array $params = [])
{
return $db = static::getCollection()->findAllBy($params, static::class);
}
final private function __construct()
{
}
public function save()
{
return static::getCollection()->save($this);
}
public function delete()
{
return static::getCollection()->deleteDocument($this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment