agyanadda@gmail.com

CodeIgniter 4 Controllers

CodeIgniter 4 Basics 1 min read Updated Dec 3, 2026 Topic 7 of 30

A controller is a class that handles requests. Controllers live in app/Controllers and usually extend BaseController.

Create a controller

php spark make:controller Posts creates app/Controllers/Posts.php in the App\Controllers namespace.

Return a response

A method can return a string, view('posts/index', $data), a redirect, or JSON with $this->response->setJSON($data).

Passing data to a view

Pass an array: keys become variables in the view. ['title' => 'Blog'] gives $title.

BaseController

app/Controllers/BaseController.php is shared by all your controllers. Put things every controller needs there — for example, helpers to load in the $helpers property, or code in initController().

Available properties

  • $this->request — the incoming request (form data, files)
  • $this->response — the response object

Sub-folders

Admin controllers can go in app/Controllers/Admin with namespace App\Controllers\Admin;. Route to them as 'Admin\Dashboard::index'.

Keep controllers short: database code belongs in models.

Example

Example — Controller passing data to a view PHP
<?php
namespace App\Controllers;

class Posts extends BaseController
{
    public function index()
    {
        $data = [
            'title' => 'Latest Posts',
            'posts' => ['Learn Routing', 'Learn Views', 'Learn Models'],
        ];

        return view('posts/index', $data);
    }
}

// app/Views/posts/index.php
// <h1><?= esc($title) ?></h1>
// <ul>
//   <?php foreach ($posts as $post): ?>
//     <li><?= esc($post) ?></li>
//   <?php endforeach ?>
// </ul>

The page shows the heading "Latest Posts" and a list of three post titles. Array keys become variables in the view.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which class do your controllers usually extend?

Exercise 2 True / False

Keys of the data array become variables in the view.

Exercise 3 Fill in the Blank

Create a controller with php spark make:___ Posts

Frequently Asked Questions

CI_Controller is the base class from CodeIgniter 3. In CodeIgniter 4, controllers extend BaseController (which extends CodeIgniter\Controller) and use namespaces.