commit | author | age
|
766451
|
1 |
<?php |
F |
2 |
namespace Framework; |
|
3 |
|
|
4 |
use App\Database; |
|
5 |
use PDO; |
|
6 |
abstract class Model |
|
7 |
{ |
4dbbdf
|
8 |
protected array $errors = []; |
d7a326
|
9 |
protected ?string $table; |
4dbbdf
|
10 |
|
F |
11 |
abstract protected function validate (array $data): void; |
|
12 |
|
|
13 |
public function __construct(private Database $database) { |
|
14 |
} |
|
15 |
|
|
16 |
|
|
17 |
protected function addError(string $field, string $message): void { |
|
18 |
$this->errors[$field] = $message; |
|
19 |
} |
|
20 |
|
|
21 |
public function getErrors(): array { |
|
22 |
return $this->errors; |
|
23 |
} |
766451
|
24 |
|
a26040
|
25 |
private function getTable() { |
F |
26 |
$parts = explode("\\", $this::class); |
|
27 |
return strtolower(array_pop($parts)); |
766451
|
28 |
} |
6704d0
|
29 |
public function getInsertID(): string { |
F |
30 |
$conn = $this->database->getConnection(); |
|
31 |
return $conn->lastInsertId(); |
|
32 |
} |
766451
|
33 |
public function findAll(): array|bool |
F |
34 |
{ |
|
35 |
$pdo = $this->database->getConnection(); |
|
36 |
|
a26040
|
37 |
$sql = "SELECT * FROM {$this->getTable()}"; |
d7a326
|
38 |
|
F |
39 |
$stmt = $pdo->query($sql); |
766451
|
40 |
|
F |
41 |
return $stmt->fetchAll(PDO::FETCH_ASSOC); |
|
42 |
} |
|
43 |
|
|
44 |
public function find(string $id) { |
|
45 |
$conn = $this->database->getConnection(); |
|
46 |
$sql = "SELECT * |
a26040
|
47 |
FROM {$this->getTable()} |
766451
|
48 |
WHERE id = :id"; |
F |
49 |
$stmt = $conn->prepare($sql); |
|
50 |
$stmt->bindValue(":id", $id, PDO::PARAM_INT); |
|
51 |
$stmt->execute(); |
|
52 |
return $stmt->fetch(PDO::FETCH_ASSOC); |
|
53 |
} |
fc5ee7
|
54 |
|
F |
55 |
public function insert(array $data) : bool { |
4dbbdf
|
56 |
$this->validate($data); |
F |
57 |
|
|
58 |
if(!empty($this->errors)) { |
7a2549
|
59 |
return false; |
F |
60 |
} |
6f90bf
|
61 |
$columns = implode(", " , array_keys($data)); |
F |
62 |
$placeholders = implode(", ", array_fill(0, count($data), "?")); |
|
63 |
|
|
64 |
$sql = "INSERT INTO {$this->getTable()} ($columns) VALUES ($placeholders)"; |
|
65 |
|
fc5ee7
|
66 |
$conn = $this->database->getConnection(); |
F |
67 |
$stmt = $conn->prepare($sql); |
b1d4d1
|
68 |
|
F |
69 |
$i = 1; |
|
70 |
foreach ($data as $value) { |
|
71 |
$type = match(gettype($value)) { |
|
72 |
"boolean" => PDO::PARAM_BOOL, |
|
73 |
"integer"=> PDO::PARAM_INT, |
|
74 |
"NULL"=> PDO::PARAM_NULL, |
|
75 |
default => PDO::PARAM_STR |
|
76 |
}; |
|
77 |
|
|
78 |
|
|
79 |
$stmt->bindValue($i++, $value, PDO::PARAM_STR); |
|
80 |
} |
|
81 |
|
fc5ee7
|
82 |
|
F |
83 |
return $stmt->execute(); |
|
84 |
} |
766451
|
85 |
} |
F |
86 |
|
|
87 |
|
|
88 |
?> |