| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- <?php
- /**
- * Classe BaseModel
- *
- * Modèle de base pour gérer les interactions avec la base de données.
- * Fournit des méthodes simples pour les opérations CRUD.
- */
- if (!class_exists('BaseModel')) {
- class BaseModel {
- protected static $table;
- private static $pdo = null;
- /**
- * Obtient une connexion PDO à la base de données.
- *
- * @return PDO
- */
- private static function getPDO() {
- if (self::$pdo === null) {
- $config = require __DIR__ . '/../../config/config.php';
- self::$pdo = new PDO(
- 'mysql:host=' . $config['db_host'] . ';dbname=' . $config['db_name'],
- $config['db_user'],
- $config['db_password']
- );
- self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- }
- return self::$pdo;
- }
- /**
- * Récupère tous les enregistrements de la table.
- *
- * @return array
- */
- public static function all() {
- $pdo = self::getPDO();
- $stmt = $pdo->query('SELECT * FROM ' . static::$table);
- return $stmt->fetchAll(PDO::FETCH_ASSOC);
- }
- /**
- * Récupère un enregistrement par son ID.
- *
- * @param int $id
- * @return array|null
- */
- public static function find($id) {
- $pdo = self::getPDO();
- $stmt = $pdo->prepare('SELECT * FROM ' . static::$table . ' WHERE id = :id');
- $stmt->execute(['id' => $id]);
- return $stmt->fetch(PDO::FETCH_ASSOC);
- }
- }
- }
|