Pass Object from Controller to View in CodeIgniter 4

Download the latest version of CodeIgniter 4 and unzip source code to new folder named LearnCodeIgniter4WithRealApps

Cut index.php and htaccess files in public folder to root folder of project

Open index.php in root folder find to line 16 replace path to Paths.php file as below:

$pathsPath = realpath(FCPATH . '/app/Config/Paths.php');

Open App.php in app/Config folder find to line 36 remove index.php string in $indexPage variable as below:

public $indexPage = '';




Create new folder named assets in public folder. In this folder, create new folders as below:

Create new folder named images in assets folder. Copy images need to use in project to images folder.

Open App.php file in app/Config folder. Set value for $baseURL variable as below:

public $baseURL = 'http://localhost:8095/LearnCodeIgniter4WithRealApps/';




Create new PHP file named Product.php in app/Models folder as below:

<?php

namespace App\Models;

class Product
{
    var $id;
    var $name;
    var $price;
    var $quantity;
    var $photo;

    function __construct($id, $name, $price, $quantity, $photo)
    {
        $this->id = $id;
        $this->name = $name;
        $this->price = $price;
        $this->quantity = $quantity;
        $this->photo = $photo;
    }
}

Create new PHP file named Demo.php in app/Controllers folder as below:

<?php

namespace App\Controllers;

use App\Models\Product;

class Demo extends BaseController
{
	public function index()
	{
		$products = array(
			new Product('p01', 'name 1', 2, 3, 'thumb1.gif'),
			new Product('p02', 'name 2', 7, 2, 'thumb1.gif'),
			new Product('p03', 'name 3', 5, 8, 'thumb3.gif')
		);
		$data['products'] = $products;
		return view('demo/index', $data);
	}
}




Create new folder named demo in views folder. In this folder, create new PHP file named index.php as below:

<html>

<head>
    <title>Demo Page</title>
</head>

<body>

    <h3>Product Info</h3>
    <table border="1" cellpadding="2" cellspacing="2">
        <tr>
            <td>Id</td>
            <td><?= $product->id; ?></td>
        </tr>
        <tr>
            <td>Name</td>
            <td><?= $product->name; ?></td>
        </tr>
        <tr>
            <td valign="top">Photo</td>
            <td><img src="<?= base_url(); ?>/public/assets/images/<?= $product->photo; ?>"></td>
        </tr>
        <tr>
            <td>Price</td>
            <td><?= $product->price; ?></td>
        </tr>
        <tr>
            <td>Quantity</td>
            <td><?= $product->quantity; ?></td>
        </tr>
        <tr>
            <td>Total</td>
            <td><?= $product->price * $product->quantity; ?></td>
        </tr>
    </table>

</body>

</html>




Open Routes.php file in app/Config folder. Set default controller as below:

$routes->get('/', 'Demo::index');




Access index action in Demo controller with following url: http://localhost:8095/LearnCodeIgniter4WithRealApps/demo/index

Output