Advertisement

Google Ad Slot: content-top

CI Controller


What is a Controller?

In CodeIgniter, a Controller is a PHP class that acts as the middleman between the user (browser) and your application logic.

It receives requests from the browser, processes them (using models if needed), and then loads the appropriate view.


Controller Structure

  • Controllers are stored in:
  • application/controllers/ (CodeIgniter 3)
  • app/Controllers/ (CodeIgniter 4)
  • File name must match the class name.
  • The class name should start with a capital letter.
Example
<?php
namespace App\Controllers;

class Home extends BaseController
{
public function index()
{
return view('welcome_message', [
'message' => 'Welcome to CodeIgniter 4!'
]);
}
}

Passing Data to Views

Example
public function about()
{
return view('about_view', [
'message' => 'About Us Page'
]);
}

Controller Action Return Types

1. Normal Website Pages (Views)

Returns a rendered HTML view with optional data passed to the view.

return view('page_view', $data);

2. Redirect to Another Route

Redirects the user to a different URL or route within the application.

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

 3. Return JSON (API)

Sends a JSON-formatted response, typically used for APIs or AJAX requests.

public function getData()
{
  return $this->response->setJSON(['a', 'b', 'c']);
}