39 lines
969 B
PHP
39 lines
969 B
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Core\Database;
|
|
use PDO;
|
|
|
|
abstract class Model
|
|
{
|
|
protected static string $table;
|
|
protected static string $primaryKey = 'id';
|
|
|
|
/**
|
|
* @return array<int, static>
|
|
*/
|
|
public static function all(): array
|
|
{
|
|
$stmt = Database::connection()->query('SELECT * FROM ' . static::$table);
|
|
$rows = $stmt->fetchAll();
|
|
return array_map(fn($row) => static::fromArray($row), $rows);
|
|
}
|
|
|
|
public static function find(int $id): ?static
|
|
{
|
|
$stmt = Database::connection()->prepare('SELECT * FROM ' . static::$table . ' WHERE ' . static::$primaryKey . ' = :id LIMIT 1');
|
|
$stmt->execute(['id' => $id]);
|
|
$row = $stmt->fetch();
|
|
if (!$row) {
|
|
return null;
|
|
}
|
|
return static::fromArray($row);
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $attributes
|
|
*/
|
|
abstract protected static function fromArray(array $attributes): static;
|
|
}
|