Codeigniter 4 – MVC Design Pattern with examples

Model

- Purpose: Represents the data and business logic of the application
- Responsibilities:
    - Interact with the database
    - Perform calculations and data processing
    - Validate data
- Example: app/Models/UserModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email', 'password'];

    public function getUser($id)
    {
        return $this->find($id);
    }
}

View

- Purpose: Responsible for rendering the user interface
- Responsibilities:
    - Display data to the user
    - Receive input from the user
    - Handle user interactions
- Example: app/Views/user_view.php

<!DOCTYPE html>
<html>
<head>
    <title>User Profile</title>
</head>
<body>
    <h1><?= $user->name ?></h1>
    <p><?= $user->email ?></p>
</body>
</html>

Controller

- Purpose: Acts as an intermediary between the Model and View
- Responsibilities:
    - Receive input from the user
    - Interact with the Model to perform business logic
    - Pass data to the View for rendering
- Example: app/Controllers/UserController.php

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\UserModel;

class UserController extends Controller
{
    public function index()
    {
        $userModel = new UserModel();
        $user = $userModel->getUser(1);
        return view('user_view', ['user' => $user]);
    }
}

MVC Flow

1. User requests a resource (e.g. /users/1)
2. Controller receives the request and interacts with the Model to perform business logic
3. Model performs calculations and data processing, and returns data to the Controller
4. Controller passes data to the View for rendering
5. View renders the user interface and displays data to the user

I hope this helps! Let me know if you have any further questions or need more information.

Leave a Reply

Shopping cart0
There are no products in the cart!
Continue shopping
0