Controllers in CodeIgniter

📘 CodeIgniter 👁 39 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

A Controller in CodeIgniter acts as the middle layer between the Model and the View. It receives user requests, processes data, and returns a response.


1. What Is a Controller?

  • Handles HTTP requests

  • Calls models to fetch/update data

  • Loads views or returns responses (JSON, text, etc.)

  • Controls application flow


2. Controller Location

app/Controllers/

3. Creating a Controller

Using Spark CLI (Recommended)

php spark make:controller Home

Manual Creation

namespace App\Controllers; class Home extends BaseController { public function index() { return "Welcome to CodeIgniter!"; } }

4. Default Controller

Configured in:

app/Config/Routes.php
$routes->setDefaultController('Home'); $routes->setDefaultMethod('index');

Access:

http://localhost:8080/

5. Controller with View

public function about() { return view('about'); }

View file:

app/Views/about.php

6. Controller with Parameters

public function profile($id) { return "User ID: $id"; }

Route:

$routes->get('user/(:num)', 'User::profile/$1');

7. Loading a Model in Controller

use App\Models\UserModel; class User extends BaseController { public function index() { $model = new UserModel(); $data['users'] = $model->findAll(); return view('users', $data); } }

8. Returning Different Responses

Text

return "Hello";

JSON

return $this->response->setJSON(['status' => 'success']);

Redirect

return redirect()->to('/login');

9. Using Request & Response

public function save() { $name = $this->request->getPost('name'); return "Saved: $name"; }

10. Controller Filters (Middleware)

Apply authentication or validation filters.

$routes->get('dashboard', 'Dashboard::index', ['filter' => 'auth']);

11. Resource Controller (REST API)

php spark make:controller Users --resource

Provides methods:

  • index()

  • show($id)

  • create()

  • update($id)

  • delete($id)


12. Best Practices

✅ Keep controllers thin
✅ Move logic to Models/Services
✅ One responsibility per controller
❌ Avoid database logic directly in controllers


Summary

  • Controllers handle user requests

  • Stored in app/Controllers

  • Communicate with Models & Views

  • Support views, JSON, redirects, APIs


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes