facut pana la video 7

This commit is contained in:
Cerbu Andrei Mihnea
2023-05-10 00:47:48 +03:00
parent 1abdc313f4
commit 90f12ab916
40 changed files with 1644 additions and 41 deletions
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace app\core;
abstract class DbModel extends Model{
abstract public function tableName(): string;
abstract public function attributes(): array;
abstract public function primaryKey(): string;
public function save(){
$tableName = $this->tableName();
$attributes = $this->attributes();
$params = array_map(fn($attr) => ":$attr", $attributes);
$statement = self::prepare("INSERT INTO $tableName ("
.implode(',', $attributes)
.") VALUES ("
.implode(',', $params)
.")"
);
foreach($attributes as $attribute){
$statement->bindValue(":$attribute", $this->{$attribute});
}
$statement->execute();
return true;
}
public static function prepare($sql){
return Application::$app->db->pdo->prepare($sql);
}
public function findOne($where){
$tableName = static::tableName();
$attributes = array_keys($where);
$sql = implode("AND ", array_map(fn($attr) => "$attr = :$attr", $attributes));
$statement = self::prepare("SELECT * from $tableName WHERE $sql");
foreach($where as $key => $item){
$statement->bindValue(":$key", $item);
}
$statement->execute();
return $statement->fetchObject(static::class);
}
}