corso https://vola.udemy.com/course/php-mvc-from-scratch/learn/lecture/40931984#overview
filippo.bertilotti
2024-05-23 85f6ec1bc8f094e769835e9836b9fab7fb9e6ace
src/Framework/Model.php
@@ -5,15 +5,36 @@
    use PDO;
    abstract class Model
    {
        protected array $errors = [];
        protected ?string $table;
        public  function __construct(private Database $database) {
        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->table}";
            $sql = "SELECT * FROM {$this->getTable()}";
            $stmt = $pdo->query($sql);
@@ -23,13 +44,44 @@
        public function find(string $id) {
            $conn = $this->database->getConnection();
            $sql = "SELECT *
                    FROM {$this->table}
                    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();
        }
    }