CodeIgniter MVC Framework

What is CodeIgniter MVC Framework?

CodeIgniter is a lightweight PHP framework that follows the MVC (Model–View–Controller) architectural pattern.

It helps you organize your application code by separating:

  1. Model → Handles data & database logic.
  2. View → Handles the presentation (HTML/CSS/JS).
  3. Controller → Handles requests and coordinates between Model & View.


CodeIgniter Folder Structure

When you install CodeIgniter 4, your main app code lives in app/ directory:


app/
 ├── Controllers/
 ├── Models/
 ├── Views/


How MVC Works in CodeIgniter

  1. User visits a URL → Controller is triggered.
  2. Controller calls the Model for data.
  3. Model returns data to the Controller.
  4. Controller sends data to a View.
  5. View displays the data in a browser.


Example: Displaying a Product List

1. Model

app/Models/ProductModel.php

Example
<?php

namespace App\Models;
use CodeIgniter\Model;

class ProductModel extends Model
{
protected $table = 'products';
protected $allowedFields = ['name', 'price', 'description'];
}

Purpose: Fetches product data from the database.

2. Controller

app/Controllers/Product.php

Example
<?php

namespace App\Controllers;
use App\Models\ProductModel;

class Product extends BaseController
{
public function index()
{
$productModel = new ProductModel();
$data['products'] = $productModel->findAll();

return view('products_list', $data);
}
}

Purpose: Loads product data from ProductModel and passes it to the view.

3. View

app/Views/products_list.php

Example
<!DOCTYPE html>
<html>
<head>
<title>Product List</title>
</head>
<body>
<h1>Our Products</h1>
<ul>
<?php foreach($products as $product): ?>
<li><?= esc($product['name']) ?> - $<?= esc($product['price']) ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>

Purpose: Displays the product list.

Routing to the Controller

app/Config/Routes.php

$routes->get('products', 'Product::index');


Flow Diagram of MVC in CodeIgniter


Browser → Controller → Model → Controller → View → Browser


Advantages of MVC in CodeIgniter

  • Clear separation of logic and presentation.
  • Easier to maintain and scale.
  • Reusable components.
  • Supports clean URLs via routing.



Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.