r117/core/Model.php · 约 1732 字符
1<?php2/**3 * 模型基类:通用 CRUD(永远用 ? 占位符防注入)4 */5class Model {6 protected PDO $pdo;7 protected string $table;89 public function __construct() { $this->pdo = Database::pdo(); }1011 public function all(array $where = []): array {12 $sql = "SELECT * FROM {$this->table}";13 $params = [];14 if ($where) {15 $parts = [];16 foreach ($where as $k => $v) { $parts[] = "$k=?"; $params[] = $v; }17 $sql .= ' WHERE ' . implode(' AND ', $parts);18 }19 $sql .= ' ORDER BY id DESC';20 $st = $this->pdo->prepare($sql);21 $st->execute($params);22 return $st->fetchAll();23 }2425 public function find(int $id): ?array {26 $st = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id=?");27 $st->execute([$id]);28 return $st->fetch() ?: null;29 }3031 public function create(array $data): int {32 $cols = array_keys($data);33 $ph = array_fill(0, count($cols), '?');34 $st = $this->pdo->prepare("INSERT INTO {$this->table} (" . implode(',', $cols) . ") VALUES (" . implode(',', $ph) . ")");35 $st->execute(array_values($data));36 return (int)$this->pdo->lastInsertId();37 }3839 public function update(int $id, array $data): bool {40 $sets = $params = [];41 foreach ($data as $k => $v) { $sets[] = "$k=?"; $params[] = $v; }42 $params[] = $id;43 $st = $this->pdo->prepare("UPDATE {$this->table} SET " . implode(',', $sets) . " WHERE id=?");44 return $st->execute($params);45 }4647 public function delete(int $id): bool {48 $st = $this->pdo->prepare("DELETE FROM {$this->table} WHERE id=?");49 return $st->execute([$id]);50 }51}52