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