无法将变量从控制器传递到视图

问题描述 投票:0回答:1

我正在尝试将值从控制器传递到视图到下拉菜单。我的代码可以在没有 MVC 架构的情况下工作,但我不知道如何将数据从控制器传递到 MVC 中的视图。所以我不知道如何将变量传递给View。

阅读分类: 类 ReadCategories { 私人 $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 [];
    }
}

}

类别控制器: 类别类别控制器{ 私人$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();
php model-view-controller view model controller
1个回答
0
投票

这不是最佳实践,但你必须使 $categories 全球化

global $categories;

$categories = $this->readCategories->getCategories();
© www.soinside.com 2019 - 2024. All rights reserved.