Created
September 21, 2021 22:25
-
-
Save 4lb0/69a002962cdec07d732a92f26304ce56 to your computer and use it in GitHub Desktop.
Doclite ActiveRecord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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