Documentation

Controller extends CI_Controller
in package

AbstractYes

Base controller class extending CI_Controller.

Provides enhanced response handling, auto-loading of models/libraries, CORS support, and hook points for response processing.

Usage:

class UserController extends \X\Controller\Controller {
  protected $model = ['UserModel', 'RoleModel'];
  protected $library = 'session';

  public function index() {
    $this->set('users', $this->UserModel->findAll())->view('user/index');
  }
}

Table of Contents

Properties

$httpResponse  : HttpResponse
HTTP response handler instance.
$library  : string|array<string|int, string>
Library(s) to auto-load on instantiation.
$model  : string|array<string|int, string>
Model(s) to auto-load on instantiation.

Methods

__construct()  : mixed
Initialize controller and auto-load models/libraries.
internalRedirect()  : void
Perform internal redirect (X-Accel-Redirect).
beforeDownload()  : void
Hook called before file download response.
beforeInternalRedirect()  : void
Hook called before internal redirect.
beforeResponse()  : void
Hook called before any response. Override to add global response processing.
beforeResponseHtml()  : void
Hook called before HTML response.
beforeResponseImage()  : void
Hook called before image response.
beforeResponseJs()  : void
Hook called before JavaScript response.
beforeResponseJson()  : void
Hook called before JSON response.
beforeResponseText()  : void
Hook called before plain text response.
beforeResponseView()  : void
Hook called before template view response.
clear()  : Controller
Clear all response data.
download()  : void
Send file download response.
error()  : void
Send error response.
html()  : void
Send HTML response.
image()  : void
Send image response.
js()  : void
Send JavaScript response.
json()  : void
Send JSON response.
set()  : Controller
Set response data.
setCorsHeader()  : Controller
Set CORS (Cross-Origin Resource Sharing) headers.
status()  : Controller
Set HTTP response status code.
text()  : void
Send plain text response.
view()  : void
Render and send Twig template response.
getReferer()  : string
Get HTTP referrer URL.

Properties

$library

Library(s) to auto-load on instantiation.

protected string|array<string|int, string> $library

Single library name or array of library names.

$model

Model(s) to auto-load on instantiation.

protected string|array<string|int, string> $model

Single model name or array of model names.

Methods

__construct()

Initialize controller and auto-load models/libraries.

public __construct() : mixed

internalRedirect()

Perform internal redirect (X-Accel-Redirect).

public internalRedirect(string $redirectPath) : void

Allows internal redirection to a location determined by a header returned from the backend. This enables the backend to authenticate and perform processing, then serve content from an internally redirected location while freeing the backend for other requests.

Parameters
$redirectPath : string

Internal redirect path.

Tags
example

Nginx configuration

# Will serve /var/www/files/myfile when passed URI /protected/myfile
location /protected {
  internal;
  alias /var/www/files;
}
example

PHP usage

class FileController extends \X\Controller\Controller {
  public function download() {
    // Authenticate user, then serve protected file
    $this->internalRedirect('/protected/secret-document.pdf');
  }
}

beforeDownload()

Hook called before file download response.

protected beforeDownload(string $referer) : void
Parameters
$referer : string

Referrer URL.

Tags
example

Log file downloads

protected function beforeDownload(string $referer) {
  \X\Util\Logger::info("File download from: {$referer}, User: " . ($_SESSION['user']['id'] ?? 'guest'));
}

beforeInternalRedirect()

Hook called before internal redirect.

protected beforeInternalRedirect(string $referer) : void
Parameters
$referer : string

Referrer URL.

Tags
example

Log protected file access

protected function beforeInternalRedirect(string $referer) {
  \X\Util\Logger::info("Protected file access from: {$referer}, User: " . $_SESSION['user']['id']);
}

beforeResponse()

Hook called before any response. Override to add global response processing.

protected beforeResponse(string $referer) : void
Parameters
$referer : string

Referrer URL.

Tags
example

Set security headers and CORS for all responses

protected function beforeResponse(string $referer) {
  $this->output->set_header('X-Content-Type-Options: nosniff');
  $this->output->set_header('X-Frame-Options: SAMEORIGIN');
  $this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
  $this->setCorsHeader('https://example.com https://app.example.com');
}

beforeResponseHtml()

Hook called before HTML response.

protected beforeResponseHtml(string $referer) : void
Parameters
$referer : string

Referrer URL.

Tags
example

Set content language header

protected function beforeResponseHtml(string $referer) {
  $this->output->set_header('Content-Language: ja');
}

beforeResponseImage()

Hook called before image response.

protected beforeResponseImage(string $referer) : void
Parameters
$referer : string

Referrer URL.

Tags
example

Set image cache headers for browser caching

protected function beforeResponseImage(string $referer) {
  $this->output->set_header('Cache-Control: public, max-age=86400');
  $this->output->set_header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT');
}

beforeResponseJs()

Hook called before JavaScript response.

protected beforeResponseJs(string $referer) : void
Parameters
$referer : string

Referrer URL.

Tags
example

Set JavaScript cache control

protected function beforeResponseJs(string $referer) {
  $this->output->set_header('Cache-Control: public, max-age=31536000');
}

beforeResponseJson()

Hook called before JSON response.

protected beforeResponseJson(string $referer) : void
Parameters
$referer : string

Referrer URL.

Tags
example

Add API response metadata

protected function beforeResponseJson(string $referer) {
  $this->set('requestId', uniqid('api_'));
  $this->set('timestamp', date('c'));
}

beforeResponseText()

Hook called before plain text response.

protected beforeResponseText(string $referer) : void
Parameters
$referer : string

Referrer URL.

Tags
example

Disable caching for plain text API responses

protected function beforeResponseText(string $referer) {
  $this->output->set_header('Cache-Control: no-cache');
  $this->output->set_header('Pragma: no-cache');
}

beforeResponseView()

Hook called before template view response.

protected beforeResponseView(string $referer) : void
Parameters
$referer : string

Referrer URL.

Tags
example

Set common template variables (logged-in user, site name, etc.)

protected function beforeResponseView(string $referer) {
  $this->set('siteName', 'My Application');
  $this->set('currentUser', $_SESSION['user'] ?? null);
  $this->set('csrfToken', $this->security->get_csrf_hash());
}

download()

Send file download response.

protected download(string $filename[, string $content = '' ][, bool $mime = false ]) : void
Parameters
$filename : string

Download filename for the browser.

$content : string = ''

File content or path to file.

$mime : bool = false

MIME type. False for auto-detection.

Tags
example

Download generated content

public function exportCsv() {
  $csv = "id,name\n1,John\n2,Jane";
  $this->download('users.csv', $csv, 'text/csv');
}
example

Download existing file

public function downloadReport() {
  $this->download('report.pdf', file_get_contents('/path/to/report.pdf'));
}

error()

Send error response.

protected error(string $message[, int $httpStatus = 500 ][, bool $forceJsonResponse = false ]) : void

Outputs an error message with the specified HTTP status code.

Parameters
$message : string

Error message to display.

$httpStatus : int = 500

HTTP status code. Default is 500.

$forceJsonResponse : bool = false

Force JSON response format. Default is false.

Tags
example

Return 404 error

public function show($id) {
  $user = $this->UserModel->get_by_id($id);
  if (!$user) {
    $this->error('User not found', 404);
    return;
  }
  $this->set('user', $user)->json();
}
example

Force JSON error response with additional data

public function create() {
  if (!$this->validate()) {
    $this->set('errors', $this->validation_errors())
         ->error('Validation failed', 400, true);
    return;
  }
}

html()

Send HTML response.

protected html(string $html) : void
Parameters
$html : string

HTML content string.

image()

Send image response.

protected image(string $imagePath) : void

Outputs an image file with appropriate Content-Type header.

Parameters
$imagePath : string

Path to the image file.

Tags
example

Display user avatar

public function avatar($userId) {
  $user = $this->UserModel->get_by_id($userId);
  $this->image(FCPATH . 'uploads/avatars/' . $user['avatar']);
}
example

Display dynamically generated image

public function thumbnail($imageId) {
  $path = $this->ImageService->getThumbnailPath($imageId);
  $this->image($path);
}

js()

Send JavaScript response.

protected js(string $js) : void
Parameters
$js : string

JavaScript code.

json()

Send JSON response.

protected json([bool $forceObject = false ][, bool $prettyrint = false ]) : void
Parameters
$forceObject : bool = false

Force object output for non-associative arrays.

$prettyrint : bool = false

Pretty-print JSON with whitespace.

Tags
example

Basic JSON response

public function getUser() {
  $user = $this->UserModel->get_by_id(1);
  $this->set('user', $user)->json();
}
// Output: {"user": {"id": 1, "name": "John"}}
example

Force object output for empty arrays

$this->set('items', [])->json(true);
// Output: {"items": }} instead of {"items": []}
example

Pretty-printed JSON for debugging

$this->set('data', $complexData)->json(false, true);

set()

Set response data.

protected set(mixed $key[, mixed|null $value = null ]) : Controller
Parameters
$key : mixed

Response data (1 arg) or field name (2 args).

$value : mixed|null = null

Field value when using 2 arguments.

Tags
example

Set single field

$this->set('username', 'John')->json();
// Output: {"username": "John"}
example

Set multiple fields

$this->set('id', 1)->set('name', 'John')->json();
// Output: {"id": 1, "name": "John"}
example

Set entire response data at once

$this->set(['id' => 1, 'name' => 'John'])->json();
// Output: {"id": 1, "name": "John"}
Return values
Controller

Method chaining.

setCorsHeader()

Set CORS (Cross-Origin Resource Sharing) headers.

protected setCorsHeader([string $origin = '*' ]) : Controller
Parameters
$origin : string = '*'

Allowed origin(s). Use '*' for all or space-separated URLs.

Tags
example

Allow all origins

$this->setCorsHeader('*');
example

Allow specific origins (space-separated)

$this->setCorsHeader('http://example.com https://example.com');
example

Set CORS for all responses via hook

protected function beforeResponse(string $referer) {
  $this->setCorsHeader('*');
}
Return values
Controller

Method chaining.

status()

Set HTTP response status code.

protected status(int $httpStatus) : Controller
Parameters
$httpStatus : int

HTTP status code (e.g., 200, 404, 500).

Return values
Controller

Method chaining.

text()

Send plain text response.

protected text(string $plainText) : void
Parameters
$plainText : string

Plain text content.

view()

Render and send Twig template response.

protected view(string $templatePath) : void
Parameters
$templatePath : string

Path to Twig template file.

Tags
example

Render a template with data

public function index() {
  $users = $this->UserModel->get_all();
  $this->set('users', $users)->set('title', 'User List')->view('user/index');
}
example

Template file (views/user/index.twig)

<h1>{{ title }}</h1>
{% for user in users %}
  <p>{{ user.name }}</p>
{% endfor %}

getReferer()

Get HTTP referrer URL.

private getReferer() : string

Returns the HTTP_REFERER if available, otherwise constructs the current URL.

Return values
string

Referrer URL.


        
On this page

Search results