Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(app): improve routing and modelling #72

Merged
merged 2 commits into from
Nov 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 20 additions & 20 deletions docker/database/start-scripts/0-init.sql
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ create table zones (
id int auto_increment primary key,
name varchar(255),
quantity int,
postal_code int,
point_id int,
postal_code int,
point_id int,
foreign key (point_id) references points(id)
);

Expand All @@ -25,8 +25,8 @@ create table elements (

create table inventory (
id int auto_increment primary key,
element_id int,
zone_id int,
element_id int,
zone_id int,
foreign key (element_id) references elements(id),
foreign key (zone_id) references zones(id)
);
Expand All @@ -35,25 +35,25 @@ create table incidences (
id int auto_increment primary key,
name varchar(255),
photo varchar(255),
element_id int,
element_id int,
description varchar(255),
incident_date timestamp,
incident_date timestamp,
foreign key (element_id) references elements(id)
);

create table roles (
id int auto_increment primary key,
role_name varchar(255)
name varchar(255) unique
);

create table workers (
id int auto_increment primary key,
company varchar(255),
name varchar(255),
dni varchar(255) unique,
dni varchar(255) unique,
password varchar(255),
email varchar(255),
role_id int,
email varchar(255),
role_id int,
created_at timestamp,
deleted_at timestamp,
updated_at timestamp,
Expand Down Expand Up @@ -84,23 +84,23 @@ create table parts (

create table routes (
id int auto_increment primary key,
distance float,
point_id int,
travel_time int,
distance float,
point_id int,
travel_time int,
foreign key (point_id) references points(id)
);

create table tasks (
id int auto_increment primary key,
task_name varchar(255),
work_order_id int,
task_name varchar(255),
work_order_id int,
description varchar(255),
inventory_id int,
machine_id int,
route_id int,
inventory_id int,
machine_id int,
route_id int,
status BIT,
part_id int,
history_id int,
part_id int,
history_id int,
created_at timestamp,
deleted_at timestamp,
foreign key (work_order_id) references work_orders(id),
Expand Down
4 changes: 2 additions & 2 deletions docker/database/start-scripts/1-seed.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
-- Insert sample roles (Admin, Manager, Worker)
INSERT INTO roles (role_name) VALUES
INSERT INTO roles (name) VALUES
('Administrador'),
('Gerente'),
('Trabajador');
Expand All @@ -8,4 +8,4 @@ INSERT INTO roles (role_name) VALUES
INSERT INTO workers (company, name, dni, password, email, role_id, created_at, updated_at, deleted_at) VALUES
('TechCorp', 'Carlos García', '12345678A', 'hashedpassword1', '[email protected]', 1, NOW(), NOW(), NULL), -- Admin
('InnovaTech', 'Ana Martínez', '23456789B', 'hashedpassword2', '[email protected]', 2, NOW(), NOW(), NULL), -- Manager
('DesignWorks', 'José Rodríguez', '34567890C', 'hashedpassword3', '[email protected]', 3, NOW(), NOW(), NULL); -- Worker
('DesignWorks', 'José Rodríguez', '34567890C', 'hashedpassword3', '[email protected]', 3, NOW(), NOW(), NULL); -- Worker
11 changes: 8 additions & 3 deletions src/app/Controllers/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\View;

class AuthController
class AuthController implements BaseController
{
public function index()
public function get()
{
View::render([
"view" => "Auth/Login",
Expand All @@ -15,4 +16,8 @@ public function index()
"data" => []
]);
}
}

public function post() {}
public function put() {}
public function delete() {}
}
9 changes: 0 additions & 9 deletions src/app/Controllers/Controller.php

This file was deleted.

13 changes: 9 additions & 4 deletions src/app/Controllers/HomeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,24 @@

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\View;
use App\Models\Worker;

class HomeController
class HomeController implements BaseController
{
public function index()
public function get()
{
$workers = Worker::getAll();
$workers = Worker::findAll();
View::render([
"view" => "Home",
"title" => "Home Page",
"layout" => "MainLayout",
"data" => ["workers" => $workers]
]);
}
}

public function post() {}
public function put() {}
public function delete() {}
}
11 changes: 11 additions & 0 deletions src/app/Core/BaseController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace App\Core;

interface BaseController
{
public function get();
public function post();
public function put();
public function delete();
}
151 changes: 151 additions & 0 deletions src/app/Core/BaseModel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
<?php

namespace App\Core;

abstract class BaseModel
{
protected int $id;

// Get the related model in a one-to-one relationship
public function belongsTo($relatedModel, $foreignKey, $ownerKey = 'id')
{
$relatedTable = $relatedModel::getTableName();
$foreignKeyValue = $this->{$foreignKey};

$query = "SELECT * FROM $relatedTable WHERE $ownerKey = :foreignKeyValue LIMIT 1";
$results = Database::prepareAndExecute($query, ['foreignKeyValue' => $foreignKeyValue]);

return !empty($results) ? $relatedModel::mapDataToModel($results[0]) : null;
}

public function delete()
{
$table = static::getTableName();

if (static::hasSoftDelete()) {
$query = "UPDATE $table SET deleted_at = NOW() WHERE id = :id";
Database::prepareAndExecute($query, ['id' => $this->id]);
} else {
$query = "DELETE FROM $table WHERE id = :id";
Database::prepareAndExecute($query, ['id' => $this->id]);
}
}

public static function find($id)
{
$table = static::getTableName();
$query = "SELECT * FROM $table WHERE id = :id LIMIT 1";
$results = Database::prepareAndExecute($query, ['id' => $id]);

if (!empty($results))
return static::mapDataToModel($results[0]);

return null;
}

public static function findAll($conditions = [])
{
$table = static::getTableName();
$query = "SELECT * FROM $table";
$params = [];

if (!empty($conditions)) {
$clauses = [];
foreach ($conditions as $key => $value) {
$clauses[] = "$key = :$key";
$params[$key] = $value;
}
$query .= " WHERE " . implode(" AND ", $clauses);
}

$results = Database::prepareAndExecute($query, $params);

return array_map(fn($row) => static::mapDataToModel($row), $results);
}

// Fetch all soft deleted records
public static function findSoftDeleted()
{
if (!static::hasSoftDelete())
return [];

$table = static::getTableName();
$query = "SELECT * FROM $table WHERE deleted_at IS NOT NULL";
$results = Database::prepareAndExecute($query);

return array_map(fn($row) => static::mapDataToModel($row), $results);
}

// Dynamically relationship fetching
public function hasMany($relatedModel, $foreignKey, $localKey = 'id')
{
$relatedTable = $relatedModel::getTableName();
$localKeyValue = $this->{$localKey};

$query = "SELECT * FROM $relatedTable WHERE $foreignKey = :localKeyValue";
$results = Database::prepareAndExecute($query, ['localKeyValue' => $localKeyValue]);

return array_map(fn($row) => $relatedModel::mapDataToModel($row), $results);
}

// Dynamically check if a table has the deleted_at column
protected static function hasSoftDelete()
{
static $softDeleteCache = [];
$table = static::getTableName();

if (!isset($softDeleteCache[$table])) {
$query = "SHOW COLUMNS FROM $table LIKE 'deleted_at'";
$result = Database::prepareAndExecute($query);
$softDeleteCache[$table] = !empty($result); // Cache the result
}

return $softDeleteCache[$table];
}

public function restore()
{
if (static::hasSoftDelete()) {
$table = static::getTableName();
$query = "UPDATE $table SET deleted_at = NULL WHERE id = :id";
Database::prepareAndExecute($query, ['id' => $this->id]);
}
}

public function save()
{
$table = static::getTableName();
$properties = get_object_vars($this);
unset($properties['id']); // Avoid saving the id in the data fields

if ($this->id) {
// Update logic
$fields = [];
foreach ($properties as $key => $value) {
$fields[] = "$key = :$key";
}
$query = "UPDATE $table SET " . implode(", ", $fields) . " WHERE id = :id";
$properties['id'] = $this->id;
} else {
// Insert logic
$fields = array_keys($properties);
$placeholders = array_map(fn($field) => ":$field", $fields);
$query = "INSERT INTO $table (" . implode(", ", $fields) . ") VALUES (" . implode(", ", $placeholders) . ")";
}

Database::prepareAndExecute($query, $properties);

if (!$this->id)
$this->id = Database::connect()->lastInsertId();
}

//* Abstract methods to enforce subclass implementation
abstract protected static function getTableName();
abstract protected static function mapDataToModel($data);

//* Getters and Setters
public function getId()
{
return $this->id;
}
}
18 changes: 8 additions & 10 deletions src/app/Core/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,18 @@ public function load($file)
public function dispatch($requestMethod, $requestUri)
{
// Check for direct match first
if (isset($this->routes[$requestMethod][$requestUri])) {
return $this->callRoute($this->routes[$requestMethod][$requestUri], $requestMethod === 'POST' ? $_POST : []);
}
if (isset($this->routes[$requestUri]))
return $this->callRoute(strtolower($requestMethod), $this->routes[$requestUri], $requestMethod === 'POST' ? $_POST : []);

// If no direct match, check for dynamic routes with parameters
foreach ($this->routes[$requestMethod] as $route => $routeInfo) {
foreach ($this->routes as $route => $routeController) {
$routePattern = preg_replace('/:\w+/', '(\w+)', $route);
$pattern = '#^' . $routePattern . '$#';

if (preg_match($pattern, $requestUri, $matches)) {
array_shift($matches); // Remove the full match
$params = $this->extractParams($route, $matches);
return $this->callRoute($routeInfo, $params, $requestMethod === 'POST' ? $_POST : []);
return $this->callRoute(strtolower($requestMethod), $routeController, $params, $requestMethod === 'POST' ? $_POST : []);
}
}

Expand All @@ -40,14 +39,13 @@ protected function extractParams($route, $matches)
return array_combine($paramNames[1], $matches);
}

protected function callRoute($routeInfo, $params = [], $postData = [])
protected function callRoute($method, $routeController, $params = [], $postData = [])
{
$controller = new $routeInfo['controller']();
$method = $routeInfo['method'];

$controller = new $routeController();

// Combine route parameters and POST data
$arguments = array_merge(array_values($params), [$postData]);

// Unpack the combined array into the method call
$controller->$method(...$arguments);
}
Expand Down
23 changes: 23 additions & 0 deletions src/app/Models/Role.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace App\Models;

use App\Core\BaseModel;

class Role extends BaseModel
{
public $name;

protected static function getTableName()
{
return 'roles';
}

protected static function mapDataToModel($data)
{
$role = new Role();
$role->id = $data['id'];
$role->name = $data['name'];
return $role;
}
}
Loading