Files
html/generated/file_04.php
2026-04-12 22:57:03 +02:00

34 lines
1.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
// 4. Models/Model.php ORM micro 60 lignes, CRUD + relations
namespace Models;
use PDO;
abstract class Model {
protected static string $table;
protected array $data = [];
public function __get($k) { return $this->data[$k]; }
public function __set($k, $v) { $this->data[$k] = $v; }
public static function pdo(): PDO {
static $pdo;
return $pdo ??= new PDO(DB_DSN, DB_USER, DB_PASS, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
}
public static function all(): array {
return static::pdo()->query("SELECT * FROM " . static::$table)->fetchAll(PDO::FETCH_CLASS, static::class);
}
public static function find(int $id): ?static {
$stmt = static::pdo()->prepare("SELECT * FROM " . static::$table . " WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetchObject(static::class) ?: null;
}
public function save(): void {
$cols = implode(',', array_keys($this->data));
$vals = implode(',', array_fill(0, count($this->data), '?'));
$sql = $this->data['id'] ?
"UPDATE " . static::$table . " SET " . implode(' = ?, ', array_keys($this->data)) . " = ? WHERE id = ?" :
"INSERT INTO " . static::$table . " ($cols) VALUES ($vals)";
$stmt = static::pdo()->prepare($sql);
$stmt->execute($this->data['id'] ? array_values(array_merge($this->data, ['id' => $this->data['id']])) : array_values($this->data));
}
public function delete(): void {
static::pdo()->prepare("DELETE FROM " . static::$table . " WHERE id = ?")->execute([$this->data['id']]);
}
}