Controllers and Responses
Relevant source files
The following files were used as context for generating this wiki page:
Controllers are the central component of a CodeIgniter 4 application, acting as the glue between incoming requests and outgoing responses. They are responsible for receiving user input, interacting with models and other libraries to process data, and then selecting a view or generating a response to be sent back to the client. This process ensures a clean separation of concerns within the application architecture.
The framework provides a powerful and flexible Response object that allows developers to build HTTP responses in an object-oriented manner. This includes setting status codes, headers, cookies, and formatting the response body as HTML, JSON, or XML. Understanding how to effectively use controllers and the response object is fundamental to building any web application with CodeIgniter.
Sources: source/incoming/controllers.rst, source/outgoing/response.rst
Controller Fundamentals
A Controller is a PHP class designed to handle a specific HTTP request. It orchestrates the logic required to generate a page or fulfill an API request.
Sources: source/incoming/controllers.rst
Creating a Controller
To create a controller, you must extend one of the framework's base controllers, typically CodeIgniter\Controller. The BaseController provides access to the request and response objects, as well as the logger. All controllers should be placed in the app/Controllers directory and use the App\Controllers namespace.
A simple controller must have at least one public method, often index(), which is called by default if no method is specified in the URL.
<?php
namespace App\Controllers;
class Helloworld extends \CodeIgniter\Controller
{
public function index()
{
return 'Hello World!';
}
}
This diagram illustrates the basic inheritance structure for a user-defined controller.
Sources: source/incoming/controllers.rst
Controller Initialization
The initController() method is provided to allow for setup tasks that need to run for every method within a controller. This is the ideal place to load helpers or instantiate models that will be used throughout the controller. It is called by the framework immediately after the controller is instantiated and before any method is executed.
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class Blog extends Controller
{
protected $helpers = ['url', 'form'];
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
// E.g.: $this->session = \Config\Services::session();
}
}
Sources: source/incoming/controllers.rst
Method Routing and Remapping
By default, the second segment of a URI determines which method in the controller gets called. If a method with that name doesn't exist, the _remap() method is invoked instead. This allows you to override the default routing behavior within a controller. The _remap() method receives the intended method name as its first argument and any additional URI segments as subsequent arguments.
The following diagram shows how an incoming request is routed to either a specific method or the _remap() function.
Sources: source/incoming/controllers.rst
Generating Responses
A controller's primary responsibility is to generate and return a response. This can be a string, a View object, or a Response object. The framework provides a comprehensive Response class to handle all aspects of the HTTP response.
Sources: source/outgoing/response.rst
The Response Object
The Response object is an instance of CodeIgniter\HTTP\Response and is always available within a controller as $this->response. It provides an object-oriented interface for building the response that will be sent to the client.
Key methods for manipulating the response are summarized in the table below:
| Method | Description |
|---|---|
setStatusCode(int $code) | Sets the HTTP status code of the response. |
setBody(string $body) | Sets the raw body content of the response. |
setHeader(string $name, string $value) | Sets a single HTTP header. |
setCookie(...) | Sets a cookie to be sent with the response. |
setJSON(mixed $data) | Formats the data as JSON and sets the Content-Type header to application/json. |
setXML(mixed $data) | Formats the data as XML and sets the Content-Type header to application/xml. |
redirect(string $uri) | Configures the response for a client-side redirect. |
Sources: source/outgoing/response.rst
Common Response Types
HTML Views
The most common response type for a web application is an HTML page. CodeIgniter provides a view() function to render view files. This function returns a string containing the rendered HTML, which can be returned directly from a controller method.
// In a controller method
$data['title'] = "My Page Title";
$data['heading'] = "Welcome to my page!";
return view('my_view_file', $data);
The view() function is a globally available common function.
Sources: source/outgoing/view_renderer.rst, source/general/common_functions.rst
JSON Responses
For API endpoints, JSON is a common response format. The setJSON() method simplifies this by automatically encoding the data and setting the correct Content-Type header.
// In a controller method
$data = ['foo' => 'bar', 'baz' => 'qux'];
return $this->response->setJSON($data);
Sources: source/outgoing/response.rst
Redirects
Redirects are handled by returning a RedirectResponse instance. The global redirect() function is the easiest way to create this object. It can be used to redirect to a new URI or back to the previous page.
// Redirect to a full site URL
return redirect()->to('http://example.com/foo');
// Redirect to a relative URI
return redirect()->to('/admin/users');
// Redirect back to the previous page, with session-based flash data
return redirect()->back()->with('message', 'Changes saved successfully.');
The redirect() function is a globally available common function.
Sources: source/outgoing/response.rst, source/general/common_functions.rst
Controller and Response Interaction Flow
The following sequence diagram illustrates the typical lifecycle of a request from the user to the final response, highlighting the roles of the Controller and Response objects.
This flow demonstrates how a controller uses other services like Session and View to gather data and construct the final Response object.
Sources: source/incoming/controllers.rst, source/outgoing/response.rst, source/outgoing/view_renderer.rst, source/libraries/sessions.rst
Summary
Controllers are the workhorses of a CodeIgniter application, directing traffic and handling the core application logic. They leverage the framework's services to process incoming requests and use the versatile Response object to craft the precise output sent back to the client. Whether returning an HTML view, a JSON payload for an API, or a simple redirect, the controller and response mechanisms provide a clean, powerful, and object-oriented approach to managing HTTP interactions.
Sources: source/incoming/controllers.rst, source/outgoing/response.rst