Codeigniter 4 – Controllers with examples

What is a Controller?

- A Controller is a class that acts as an intermediary between the Model and View.
- It receives input from the user, interacts with the Model to perform business logic, and passes data to the View for rendering.

Creating a Controller

- Create a new file in the app/Controllers directory (e.g. UserController.php).
- Extend the CodeIgniter\Controller class.
- Define methods for handling requests (e.g. index, create, edit, delete).

Example: app/Controllers/UserController.php

<?php

namespace App\Controllers;

use CodeIgniter\Controller;

class UserController extends Controller
{
    public function index()
    {
        // Handle the request
    }

    public function create()
    {
        // Handle the request
    }

    public function edit($id)
    {
        // Handle the request
    }

    public function delete($id)
    {
        // Handle the request
    }
}

Controller Methods

- index(): Handles the default request (e.g. /users).
- create(): Handles the create request (e.g. /users/create).
- edit($id): Handles the edit request (e.g. /users/1/edit).
- delete($id): Handles the delete request (e.g. /users/1/delete).

Passing Data to the View

- Use the view() function to render the View and pass data to it.
- Pass an array of data as the second argument to the view() function.

Example:

public function index()
{
    $data['users'] = $this->userModel->getAllUsers();
    return view('user_view', $data);
}

Using Models in Controllers

- Create an instance of the Model class in the Controller method.
- Use the Model methods to perform business logic.

Example:

public function index()
{
    $userModel = new UserModel();
    $data['users'] = $userModel->getAllUsers();
    return view('user_view', $data);
}

Using Helpers in Controllers

- Load the Helper class in the Controller method using the helper() function.
- Use the Helper methods to perform tasks.

Example:

public function index()
{
    helper('form');
    // Use the form helper methods
}

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