Initial commit

This commit is contained in:
Hamza-Ayed
2026-05-21 00:40:47 +03:00
commit 8e429d8313
14 changed files with 1152 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
<?php
namespace App\Models;
use App\Core\Database;
/**
* Base database model implementing generic active-record CRUD routines.
*/
abstract class BaseModel
{
protected static string $table = '';
protected static string $primaryKey = 'id';
/**
* Retrieve all records
*/
public static function all(): array
{
$table = static::$table;
return Database::select("SELECT * FROM {$table}");
}
/**
* Find a record by its primary key
*
* @param mixed $id
* @return array|null
*/
public static function find($id): ?array
{
$table = static::$table;
$primaryKey = static::$primaryKey;
return Database::selectOne("SELECT * FROM {$table} WHERE {$primaryKey} = :id LIMIT 1", ['id' => $id]);
}
/**
* Insert a new record
*
* @param array $data Assocation array of columns and values
* @return string Last inserted primary key ID
*/
public static function create(array $data): string
{
$table = static::$table;
$columns = implode(', ', array_keys($data));
$placeholders = ':' . implode(', :', array_keys($data));
$sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})";
return Database::insert($sql, $data);
}
/**
* Update an existing record
*
* @param mixed $id Primary key ID
* @param array $data Associative array of changes
* @return int Affected rows count
*/
public static function update($id, array $data): int
{
$table = static::$table;
$primaryKey = static::$primaryKey;
$sets = [];
foreach (array_keys($data) as $column) {
$sets[] = "{$column} = :{$column}";
}
$setSql = implode(', ', $sets);
$sql = "UPDATE {$table} SET {$setSql} WHERE {$primaryKey} = :_id";
$params = $data;
$params['_id'] = $id;
return Database::execute($sql, $params);
}
/**
* Delete record by ID
*/
public static function delete($id): int
{
$table = static::$table;
$primaryKey = static::$primaryKey;
$sql = "DELETE FROM {$table} WHERE {$primaryKey} = :id";
return Database::execute($sql, ['id' => $id]);
}
}