🚀 مُصادَق: الإطلاق الأولي للنظام المتكامل
This commit is contained in:
66
app/Models/BaseModel.php
Normal file
66
app/Models/BaseModel.php
Normal file
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Core\Database;
|
||||
use PDO;
|
||||
|
||||
abstract class BaseModel
|
||||
{
|
||||
protected string $table;
|
||||
protected string $primaryKey = 'id';
|
||||
protected array $fillable = [];
|
||||
|
||||
protected function db(): PDO
|
||||
{
|
||||
return Database::getInstance();
|
||||
}
|
||||
|
||||
public function find(string $id): ?array
|
||||
{
|
||||
$stmt = $this->db()->prepare("SELECT * FROM {$this->table} WHERE {$this->primaryKey} = ? AND deleted_at IS NULL LIMIT 1");
|
||||
$stmt->execute([$id]);
|
||||
return $stmt->fetch() ?: null;
|
||||
}
|
||||
|
||||
public function create(array $data): string|bool
|
||||
{
|
||||
$columns = implode(', ', array_keys($data));
|
||||
$placeholders = implode(', ', array_fill(0, count($data), '?'));
|
||||
|
||||
$sql = "INSERT INTO {$this->table} ({$columns}) VALUES ({$placeholders})";
|
||||
$stmt = $this->db()->prepare($sql);
|
||||
|
||||
if ($stmt->execute(array_values($data))) {
|
||||
return $data[$this->primaryKey] ?? $this->db()->lastInsertId();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function update(string $id, array $data): bool
|
||||
{
|
||||
$sets = [];
|
||||
foreach (array_keys($data) as $column) {
|
||||
$sets[] = "{$column} = ?";
|
||||
}
|
||||
$setString = implode(', ', $sets);
|
||||
|
||||
$sql = "UPDATE {$this->table} SET {$setString} WHERE {$this->primaryKey} = ?";
|
||||
$stmt = $this->db()->prepare($sql);
|
||||
|
||||
$params = array_values($data);
|
||||
$params[] = $id;
|
||||
|
||||
return $stmt->execute($params);
|
||||
}
|
||||
|
||||
public function delete(string $id): bool
|
||||
{
|
||||
$sql = "UPDATE {$this->table} SET deleted_at = NOW() WHERE {$this->primaryKey} = ?";
|
||||
$stmt = $this->db()->prepare($sql);
|
||||
return $stmt->execute([$id]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user