Download and Install 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 Assets Folder
Create new folder named assets in public folder. In this folder, create new folders as below:
Images Folder
Create new folder named images in assets folder. Copy images need to use in project to images folder.
Set BASE URL
Open App.php file in app/Config folder. Set value for $baseURL variable as below:
public $baseURL = 'http://localhost:8095/LearnCodeIgniter4WithRealApps/';
Create Product Entity
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 Controller
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 View
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 List</h3>
<table border="1" cellpadding="2" cellspacing="2">
<tr>
<th>Id</th>
<th>Name</th>
<th>Photo</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub Total</th>
</tr>
<?php foreach($products as $product) { ?>
<tr>
<td><?php echo $product->id; ?></td>
<td><?php echo $product->name; ?></td>
<td><img src="<?php echo base_url(); ?>/public/assets/images/<?php echo $product->photo; ?>"></td>
<td><?php echo $product->price; ?></td>
<td><?php echo $product->quantity; ?></td>
<td><?php echo $product->price * $product->quantity; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
Define Routes
Open Routes.php file in app/Config folder. Set default controller as below:
$routes->get('/', 'Demo::index');
Structure of CodeIgniter 4 Project
Run Application
Access index action in Demo controller with following url: http://localhost:8095/LearnCodeIgniter4WithRealApps/demo/index
Output