Create User & Media models/controllers, remove Task & Project

# Created:

#  - UserModel + UserController

#  - MediaModel + MediaController

# Removed:

#  - TaskModel + TaskController

#  - ProjectModel + ProjectController
This commit is contained in:
MosLaptop\Not.Reda 2025-09-05 12:04:18 +02:00
parent 69dd02eb91
commit 4efea20fae
18 changed files with 405 additions and 227 deletions

View File

@ -0,0 +1,35 @@
<?php
namespace ppb\Controller;
use ppb\Model\MediaModel;
class MediaController {
public function __construct() {}
// GET all media
public function get($data = null): void
{
$model = new MediaModel();
$result = $model->getAll();
header('Content-Type: application/json');
echo json_encode($result);
}
// ADD new media
public function add($data): void
{
$model = new MediaModel();
$result = $model->insert($data);
header('Content-Type: application/json');
echo json_encode($result);
}
// REMOVE media by id
public function remove($data): void
{
$model = new MediaModel();
$result = $model->remove($data);
header('Content-Type: application/json');
echo json_encode($result);
}
}

View File

@ -1,8 +1,8 @@
<?php
namespace App\Controller;
namespace ppb\Controller;
use ppb\Model\ProjectModel;
use App\Model\ProjectModel;
class ProjectController {
@ -44,4 +44,9 @@ class ProjectController {
}
echo '</table>';
}
public function addNewMediaType($data): void
{
$model = new ProjectModel();
$model->insertNewMediaType($data);
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace ppb\Controller;
use ppb\Model\TaskModel;
class TaskController {
public function __construct()
{
}
public function writeTask($data): void
{
$model = new TaskModel();
$model->insertTask($data);
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace ppb\Controller;
use ppb\Model\UserModel;
class UserController {
public function __construct() {}
// GET all users
public function get($data = null): void
{
$model = new UserModel();
$result = $model->getAll();
header('Content-Type: application/json');
echo json_encode($result);
}
// CREATE new user
public function create($data): void
{
$model = new UserModel();
$result = $model->insert($data);
header('Content-Type: application/json');
echo json_encode($result);
}
// UPDATE user info
public function set($data): void
{
$model = new UserModel();
$result = $model->update($data);
header('Content-Type: application/json');
echo json_encode($result);
}
}

71
Model/MediaModel.php Normal file
View File

@ -0,0 +1,71 @@
<?php
namespace ppb\Model;
use ppb\Library\Msg;
class MediaModel extends Database
{
public function getAll()
{
$pdo = $this->linkDB();
$sql = "SELECT * FROM media";
try {
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare($sql);
$sth->execute();
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
$sth->closeCursor();
$pdo = null;
return $result;
} catch (\PDOException $e) {
return ["error" => $e->getMessage()];
}
}
public function insert($data)
{
$pdo = $this->linkDB();
$sql = "INSERT INTO media (uid, tid, name, length)
VALUES (:uid, :tid, :name, :length)";
try {
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare($sql);
$sth->bindValue(':uid', $data['uid']);
$sth->bindValue(':tid', $data['tid']);
$sth->bindValue(':name', $data['name']);
$sth->bindValue(':length', $data['length'] ?? null);
$sth->execute();
$sth->closeCursor();
$pdo = null;
return ["success" => true, "message" => "Media inserted"];
} catch (\PDOException $e) {
return ["error" => $e->getMessage()];
}
}
public function remove($data)
{
$pdo = $this->linkDB();
$sql = "DELETE FROM media WHERE mid = :mid";
try {
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare($sql);
$sth->bindValue(':mid', $data['mid']);
$sth->execute();
$sth->closeCursor();
$pdo = null;
return ["success" => true, "message" => "Media removed"];
} catch (\PDOException $e) {
return ["error" => $e->getMessage()];
}
}
}

49
Model/ProjectModel.php Normal file
View File

@ -0,0 +1,49 @@
<?php
namespace ppb\Model;
use ppb\Library\Msg;
class ProjectModel extends Database
{
public function readProject()
{
$pdo = $this->linkDB();
$sql = "SELECT * FROM users";
try {
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $e) {
new Msg(true, null, $e);
}
$sth = $pdo->prepare($sql);
$sth->execute();
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
$sth->closeCursor();
$pdo = null;
// fetch all
return $result;
}
public function insertNewMediaType($data)
{
$pdo = $this->linkDB();
try {
// it should add an new type and it is Files
$sql = "INSERT INTO media_types (id, type)
VALUES (:id, :type)";
$sth = $pdo->prepare($sql);
$sth-> execute([
':id' => $this->createUUID(),
':type' => $data['Files']
]);
$pdo = null;
new Msg(false, "Medientyp erfolgreich eingefügt.");
} catch (\PDOException $e) {
new Msg(true, 'Fehler beim Einfügen des Medientyps', $e);
}
}
}

37
Model/TaskModel.php Normal file
View File

@ -0,0 +1,37 @@
<?php
namespace ppb\Model;
use ppb\Library\Msg;
class TaskModel extends Database {
public function insertTask($data) {
$pdo = $this->linkDB();
try {
$sql = "INSERT INTO task (id, userId, projectId, title, expense, dueDate, priorityId, done )
VALUES (:id,:userId,:projectId, :title, :expense, :dueDate, :priorityId, :done)";
$sth = $pdo->prepare($sql);
$sth-> execute([
':id' => $this->createUUID(),
':userId' => '4f141df7-3c0a-11e8-b046-2c4d544f8fe0',
':projectId' => $data['projectId'],
':title' => $data['title'],
':expense' => str_replace("," , "." ,$data['expense']),
':dueDate' => date("Y-m-d", strtotime($data['dueDate'])),
':priorityId' => $data['priorityId'],
':done' => 0
]);
$pdo = null;
new Msg(false, "Task erfolgreich eingefügt.");
} catch (\PDOException $e) {
new Msg(true, 'Fehler beim Einfügen des Tasks', $e);
}
}
}

76
Model/UserModel.php Normal file
View File

@ -0,0 +1,76 @@
<?php
// Mohammad Reda Mohammad
namespace ppb\Model;
use ppb\Library\Msg;
class UserModel extends Database
{
public function getAll()
{
$pdo = $this->linkDB();
$sql = "SELECT uid, username, email, created_at FROM users"; // dont expose password hash
try {
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare($sql);
$sth->execute();
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
$sth->closeCursor();
$pdo = null;
return $result;
} catch (\PDOException $e) {
return ["error" => $e->getMessage()];
}
}
public function insert($data)
{
$pdo = $this->linkDB();
$sql = "INSERT INTO users (username, email, password_hash)
VALUES (:username, :email, :password_hash)";
try {
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare($sql);
$sth->bindValue(':username', $data['username']);
$sth->bindValue(':email', $data['email']);
$sth->bindValue(':password_hash', password_hash($data['password'], PASSWORD_BCRYPT));
$sth->execute();
$sth->closeCursor();
$pdo = null;
return ["success" => true, "message" => "User created"];
} catch (\PDOException $e) {
return ["error" => $e->getMessage()];
}
}
public function update($data)
{
$pdo = $this->linkDB();
$sql = "UPDATE users
SET username = :username,
email = :email
WHERE uid = :uid";
try {
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare($sql);
$sth->bindValue(':uid', $data['uid']);
$sth->bindValue(':username', $data['username']);
$sth->bindValue(':email', $data['email']);
$sth->execute();
$sth->closeCursor();
$pdo = null;
return ["success" => true, "message" => "User updated"];
} catch (\PDOException $e) {
return ["error" => $e->getMessage()];
}
}
}

View File

@ -1,6 +1,5 @@
<?php
namespace App\Config;
namespace ppb\Model;
use ppb\Library\Msg;

57
SQL/tables.sql Normal file
View File

@ -0,0 +1,57 @@
-- -- Users Table
-- CREATE TABLE users (
-- uid INT AUTO_INCREMENT PRIMARY KEY,
-- username VARCHAR(50) NOT NULL,
-- email VARCHAR(100) NOT NULL UNIQUE,
-- password_hash VARCHAR(255) NOT NULL, -- store a hashed password, never plain text
-- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-- );
-- -- Media Types Table (e.g., Film, Music)
-- CREATE TABLE media_types (
-- tid INT AUTO_INCREMENT PRIMARY KEY,
-- type_name VARCHAR(50) NOT NULL
-- );
-- -- Media Table
-- CREATE TABLE media (
-- mid INT AUTO_INCREMENT PRIMARY KEY,
-- uid INT NOT NULL,
-- tid INT NOT NULL,
-- name VARCHAR(100) NOT NULL,
-- length INT,
-- watched_count INT DEFAULT 0,
-- favorite BOOLEAN DEFAULT 0,
-- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
-- FOREIGN KEY (uid) REFERENCES users(uid) ON DELETE CASCADE,
-- FOREIGN KEY (tid) REFERENCES media_types(tid) ON DELETE CASCADE
-- );
-- -- Preferences Table
-- CREATE TABLE preferences (
-- pid INT AUTO_INCREMENT PRIMARY KEY,
-- uid INT NOT NULL,
-- theme_mode TINYINT(1) DEFAULT 0, -- 0 = Light, 1 = Dark
-- preferred_path VARCHAR(255),
-- device_name VARCHAR(100),
-- FOREIGN KEY (uid) REFERENCES users(uid) ON DELETE CASCADE
-- );
-- -- Playlists Table (Future feature: Group media items into playlists)
-- CREATE TABLE playlists (
-- plid INT AUTO_INCREMENT PRIMARY KEY,
-- uid INT NOT NULL,
-- name VARCHAR(100) NOT NULL,
-- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
-- FOREIGN KEY (uid) REFERENCES users(uid) ON DELETE CASCADE
-- );
-- -- Playlist Items Table (Many-to-Many relation: media in playlists)
-- CREATE TABLE playlist_items (
-- plid INT NOT NULL,
-- mid INT NOT NULL,
-- added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
-- PRIMARY KEY (plid, mid),
-- FOREIGN KEY (plid) REFERENCES playlists(plid) ON DELETE CASCADE,
-- FOREIGN KEY (mid) REFERENCES media(mid) ON DELETE CASCADE
-- );

View File

@ -1,20 +0,0 @@
<?php
use App\Config\Database;
require_once __DIR__ . '/../App/Config/Database.php'; // Adjusted to use a relative path
try {
// Create an instance of the Database class
$db = new class extends Database {};
// Establish a connection using the linkDB method
$pdo = $db->linkDB();
// If the connection is successful
echo "Connected successfully using PDO";
} catch (Exception $e) {
// Handle connection error
error_log($e->getMessage()); // Log the error message
echo "An error occurred while connecting to the database. Please try again later.";
}

View File

@ -1,40 +0,0 @@
<?php
class ControllerTester
{
public function testController($controllerPath, $methodName, $params = [])
{
if (!file_exists($controllerPath)) {
return "Error: Controller file not found at path: $controllerPath";
}
require_once $controllerPath;
// Extract the class name from the file path
$className = basename($controllerPath, '.php');
if (!class_exists($className)) {
return "Error: Class $className not found in the controller file.";
}
$controller = new $className();
if (!method_exists($controller, $methodName)) {
return "Error: Method $methodName not found in class $className.";
}
// Call the method with parameters
return call_user_func_array([$controller, $methodName], $params);
}
}
// Example usage
$tester = new ControllerTester();
$controllerPath = '../App/Controller/ProjectController.php'; // Path to the controller file
$methodName = 'getAllRecords'; // Replace with the method you want to test
$params = []; // Replace with the parameters for the method
$result = $tester->testController($controllerPath, $methodName, $params);
echo '<pre>';
print_r($result);
echo '</pre>';

View File

@ -1,65 +0,0 @@
<?php
namespace App\Controller;
use App\Model\ExampleModel;
use Exception;
class ExampleController
{
private $model;
public function __construct()
{
// Initialize the ExampleModel
$this->model = new ExampleModel();
}
/**
* Write a new record to the database
*
* @param array $data
* @return void
*/
public function writeRecord(array $data): void
{
try {
$this->model->insertRecord($data);
} catch (Exception $e) {
// Log the error or handle it as needed
error_log("Error writing record: " . $e->getMessage());
throw new Exception("Failed to write record.");
}
}
/**
* Get all records from the database
*
* @return array
*/
public function getAllRecords(): array
{
try {
return $this->model->fetchAllRecords();
} catch (Exception $e) {
// Log the error or handle it as needed
error_log("Error fetching records: " . $e->getMessage());
return [];
}
}
/**
* Delete a record by ID
*
* @param int $id
* @return void
*/
public function deleteRecord(int $id): void
{
try {
$this->model->removeRecord($id);
} catch (Exception $e) {
// Log the error or handle it as needed
error_log("Error deleting record: " . $e->getMessage());
throw new Exception("Failed to delete record.");
}
}
}

View File

@ -1,55 +0,0 @@
<?php
namespace App\Model;
class ExampleModel
{
private $records = [];
public function __construct()
{
// Initialize with some example data
$this->records = [
['id' => 1, 'name' => 'Example 1', 'value' => 100],
['id' => 2, 'name' => 'Example 2', 'value' => 200],
['id' => 3, 'name' => 'Example 3', 'value' => 300],
];
}
/**
* Insert a new record into the example data
*
* @param array $data
* @return void
*/
public function insertRecord(array $data): void
{
$this->records[] = [
'id' => count($this->records) + 1,
'name' => $data['name'] ?? 'Unnamed',
'value' => $data['value'] ?? 0,
];
}
/**
* Fetch all records from the example data
*
* @return array
*/
public function fetchAllRecords(): array
{
return $this->records;
}
/**
* Remove a record by ID from the example data
*
* @param int $id
* @return void
*/
public function removeRecord(int $id): void
{
$this->records = array_filter($this->records, function ($record) use ($id) {
return $record['id'] !== $id;
});
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace App\Model;
use App\Config\Database;
use ppb\Library\Msg;
class ProjectModel extends Database
{
public function readProject()
{
$pdo = $this->linkDB();
$sql = "SELECT id, name FROM project";
try {
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $e) {
new Msg(true, null, $e);
}
$sth = $pdo->prepare($sql);
$sth->execute();
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
$sth->closeCursor();
$pdo = null;
// fetch all
return $result;
}
}

View File

View File

View File

@ -1,18 +1,25 @@
<?php
define('API', 'restAPI.php'); // NICHT VERAENDERN!!!
const API = 'restAPI.php'; // NICHT VERAENDERN!!!
$url = "http://localhost/VPR_Backend/" . API;
// $filepath = "c:\\xampp\\htdocs\\2022_BEE_PBAT3H19AB\\taskit\\";
// $filepath = "c:\\xampp\\htdocs\\VPR_Backend\\media\\";
/**
* Options for get all projetcs
* Options for get all projects
*/
$defaults = array(
CURLOPT_URL => $url . '/project',
// $defaults = [
// CURLOPT_URL => "{$url}/project",
// // CURLOPT_COOKIEFILE => $filepath . 'cookie.txt', // set cookie file to given file
// // CURLOPT_COOKIEJAR => $filepath . 'cookie.txt', // set same file as cookie jar
// CURLOPT_CUSTOMREQUEST => "GET"
// ];
// Options for get the userController
$defaults = [
CURLOPT_URL => "{$url}/user",
// CURLOPT_COOKIEFILE => $filepath . 'cookie.txt', // set cookie file to given file
// CURLOPT_COOKIEJAR => $filepath . 'cookie.txt', // set same file as cookie jar
CURLOPT_CUSTOMREQUEST => "GET"
);
];
/**
* Options for get all tasks
@ -114,15 +121,12 @@
// );
// session_write_close();
$ch = curl_init();
curl_setopt_array($ch, ($defaults));
$ch = curl_init();
curl_setopt_array($ch, $defaults);
curl_exec($ch);
if(curl_error($ch)) {
print(curl_error($ch));
}
curl_close($ch);
// session_start();
?>
// session_start();