corso https://vola.udemy.com/course/php-mvc-from-scratch/learn/lecture/40931984#overview
filippo.bertilotti
2024-05-22 7a25499e3b44eb42756b21deb4d2368bc3ce517e
creazione gestore di errore in caso di campi vuoti e specifica di quale campo manca (parte 127 e 128)
3 files modified
23 ■■■■■ changed files
src/App/Controllers/products.php 2 ●●●●● patch | view | raw | blame | history
src/App/Models/product.php 18 ●●●●● patch | view | raw | blame | history
src/Framework/Model.php 3 ●●●●● patch | view | raw | blame | history
src/App/Controllers/products.php
@@ -44,5 +44,7 @@
        ];
        
        var_dump($this->model->insert($data));
        print_r($this->model->getErrors());
    }
}
src/App/Models/product.php
@@ -5,5 +5,21 @@
    use PDO;
    use Framework\Model;
    class Product extends Model {
        protected ?string $table = "product";
        //protected ?string $table = "product";
        protected array $errors = [];
        protected function addError(string $field, string $message): void {
            $this->errors[$field] = $message;
        }
        protected function validate(array $data): bool {
            if(empty($data["name"])) {
                $this->addError("name","Name is required");
            }
            return empty($this->errors);
        }
        public function getErrors(): array {
            return $this->errors;
        }
    }
src/Framework/Model.php
@@ -36,6 +36,9 @@
        }
        public function insert(array $data) : bool {
            if( ! $this->validate($data)) {
                return false;
            }
            $columns = implode(", " , array_keys($data));
            $placeholders = implode(", ", array_fill(0, count($data), "?"));