I am trying to pass values from the controller to the view to a drop down menu. I got the code to work without MVC architecture, but I don't know how to pass the data from the controller to the view in MVC. So I don't know how to pass the variable to the View.
ReadCategories: class ReadCategories { private $db;
public function __construct($pdoConnection) {
$this->db = $pdoConnection;
}
public function getCategories() {
try {
$query = $this->db->prepare("SELECT * FROM categories");
$query->execute();
return $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
error_log("Error fetching categories: " . $e->getMessage());
return [];
}
}
}
CategoryController: class CategoryController { private $readCategories;
public function __construct(ReadCategories $readCategories) {
$this->readCategories = $readCategories;
}
public function handleRequest() {
session_start();
if (!isset($_SESSION['username']) || empty($_SESSION['username'])) {
header("Location: /technique-db/app/MVC/View/LoginView.php");
exit();
}
$categories = $this->readCategories->getCategories();
include __DIR__ . '/../View/AddItemsView.php';
}
}
$pdoConnection = require __DIR__ . '/../Config/db.php'; // Include the database connection file and get the PDO connection
// Check if the database connection is a valid PDO instance
if (!$pdoConnection instanceof PDO) {
echo "Database connection failed.";
exit(); // Terminate the script if the database connection failed
}
$readCategories = new ReadCategories($pdoConnection);
// Route to CategoryController if requested
if (isset($_GET['action']) && $_GET['action'] === 'additems') {
$categoryController = new CategoryController($readCategories);
$categoryController->handleRequest();
exit();
}
// Create a new LoginUser object with the PDO connection
$loginUser = new LoginUser($pdoConnection);
// Create a new IndexController object with the LoginUser object
$indexController = new IndexController($loginUser);
// Handle the request
$indexController->handleRequest();
It is not a best practice but you have to make $categories global
global $categories;
$categories = $this->readCategories->getCategories();
you should also make global in included file