Page 4: View Creation & Data Passing

4. View Creation and Data Passing

The View handles the user interface and displays the data passed from the Controller. PHP code should be minimized for readability.

4.1. Creating a View File (app/Views)

Create the app/Views/product_list.php file and mix HTML markup with PHP to output the data.

<!-- app/Views/product_list.php -->
<h1>Product List</h1>
<?php foreach ($products as $product): ?>
    <div>
        <h3><?= esc($product['name']) ?></h3>
        <p>Price: <?= esc($product['price']) ?></p>
    </div>
<?php endforeach ?>

4.2. Passing Data from Controller to View

The Controller fetches data via the Model and passes it to the View function as an array.

// app/Controllers/Products.php (partial update)
public function list()
{
    $model = new \App\Models\ProductModel();
    $data['products'] = $model->getAllProducts();
    
    // Pass the $data array to the View
    return view('product_list', $data); 
}

Inside the View file, the passed data can be used directly as PHP variables (e.g., $products).