Luminova Framework

PHP Luminova: View Response Object

Last updated: 2026-11-28 20:57:12

Send response content, JSON, or files with an explicit HTTP status and headers.

Luminova’s View Response class represents HTTP output from a controller or route callback. A response can carry a status code, headers, and body. When a controller returns the response object, Luminova’s router sends it to the client.

For controller actions that render a template, see Template View Rendering.

Example

A JSON endpoint can attach its payload and return the response object with the appropriate status code.


Key Features

  • Direct Output: Send raw data or processed content straight from controllers or routes.
  • Global Helper Access: Call the Response instance using a global helper — no need to new it manually.

Limitations

  • No Built-in Caching: You’ll need to handle caching yourself if required.
  • No Template Engine Support: This class doesn’t use template engines like Smarty or Twig.

Note:

This class does not behave like Luminova\Http\Message\Response and it does not implement Psr\Http\Message\ResponseInterface. It’s built for simplicity and focuses on sending or downloading content.

When to Use

Use this response class when building simple APIs responses, returning JSON, delivering files to the client, or streaming content cases where the template view system is not needed.


Examples

Creating a Response Instance

You can create a Response object in two ways:

Direct instantiation

Use this when you want a fresh, explicit instance.

use Luminova\Template\Response;

$response = new Response(status: 200);

Using the global helper

This returns a shared instance without importing the class manually (easy access).

use function Luminova\Funcs\response;

$response = response(200);

Sending Content to the Client

The Response class provides simple methods for sending different types of output.

JSON response (common for APIs):

$response->json([
    'status' => 'OK',
    'message' => 'API response body',
]);

Raw HTML:

$response->html('<p>Hello World!</p>');

Custom content with custom headers:

$response->render('<content body>', [
    'Content-Type' => 'text/custom',
]);

File download:

$response->download(
    '/path/to/file.txt',
    name: 'report.txt'
);

Returning a Response from Controllers

This example shows how to return data from a controller method as an HTTP response:

// /app/Controllers/Http/RestController.php

use Luminova\Template\Response;
use Luminova\Attributes\Route;

#[Route('/api/info', methods: ['GET'])]
public function apiInfo(): Response
{
    // Create a JSON response with HTTP 200 (OK)
    return new Response(status: 200, content: [
        'status' => 'OK',
        'info' => ['PHP', 'Luminova']
    ]);
}

Returning a Response in Middleware

You can also return a response directly inside middleware logic.If authentication fails, you can send an error response with asFailed() to indicate the middleware did not pass.

// /app/Controllers/Http/RestController.php

use Luminova\Template\Response;
use Luminova\Attributes\Route;

#[Route('/api/(:root)', methods: ['GET'], middleware: Route::BEFORE_MIDDLEWARE)]
public function middleware(): int|Response
{
    // Allow request if user is online
    if ($this->app->session->isOnline()) {
        return STATUS_SUCCESS; // Continue routing
    }

    // Otherwise, return a failed response (HTTP 401)
    return (new Response(status: 401))->asFailed()->setContent(['error' => 'Access denied']);
}

Class Definition


Methods

__construct

Initialize a response object with optional content, headers, compression, and HTML minification. When you provide content, the response processes it immediately. Use output() to send the response or getResult() to retrieve the result.

public function __construct(
    string|array|object|null $content = null,
    private int $status = 200,
    private array $headers = [],
    private bool $compress = false,
    private bool $minify = false,
    private ?array $preserveTags = null
)

Parameters:

ParameterTypeDescription
$contentstring\|array<int\|string,mixed>\|object\|nullContent to process immediately (default null).
$statusintHTTP status code (default 200).
$headersarray<string, mixed>Response headers keyed by name (default []).
$compressboolEnable response compression (default false).
$minifyboolEnable HTML minification (default false).
$preserveTagsstring[]&#124;nullHTML tags whose contents are preserved during minification, such as pre and code. The default null uses output.minify.preserve.tags.

Throws:

Luminova\Exceptions\ResponseException - If content is not null and error was encountered while processing.


getStatusCode

Get the current HTTP status code.

public function getStatusCode(): int

Return:

int - Return the current HTTP status code.


getHeaders

Retrieve all set HTTP headers.

public function getHeaders(): array

Return:

array<string,mixed> - Return an array of all headers.


getHeader

Retrieve the value of a specific HTTP header.

public function getHeader(string $name): mixed

Parameters:

ParameterTypeDescription
$namestringThe name of the header.

Return:

mixed - Return the header value, or null if not found.



getResult

Read the processed response without sending it. Returns an empty array before content has been prepared.

public function getResult(): array

Return:

array<string,mixed> - Processed response data.

KeyTypeDescription
exitintFramework exit status.
statusintHTTP status at the time the content was prepared.
headersarray<string,mixed>Prepared response headers.
contentsstringProcessed response body.

Examples:

use Luminova\Template\Response;

$result = (new Response())
    ->setContent(['ready' => true])
    ->getResult();

echo $result['contents'];

clearHeaders

Clear all previously set HTTP headers.

public function clearHeaders(): void

clearRedirects

Clear any redirects set in the response headers.

public function clearRedirects(): void

Return:

void - Clears redirect headers from the response.


hasRedirects

Check if the response headers contain any redirects.

public function hasRedirects(): bool

Return:

bool - Return true if redirects are set, false otherwise.


setStatus

Set the HTTP status code for the response.

public function setStatus(int $status): self

Parameters:

ParameterTypeDescription
$statusintThe HTTP status code to be set (e.g, 200).

Return:

Response - Return instance of the Response class.


enableCompression

Enable or disable content compression using encoding (e.g., gzip, deflate).

public function enableCompression(bool $compress = true): self

Parameters:

ParameterTypeDescription
$compressboolWhether to compress content (default: true).

Return:

Response - Return instance of the Response class.


enableHtmlMinifier

Configure HTML minification before preparing the response content. Supply tag names to preserve their contents and button settings to customize code blocks.

public function enableHtmlMinifier(
    bool $minify = true,
    ?array $preserveTags = null,
    ?array $codeBlockButtons = null
): self

Parameters:

ParameterTypeDescription
$minifyboolEnable HTML minification (default: true).
$preserveTagsarray<int,string>\|nullTags whose contents should be preserved (default: null).
$codeBlockButtonsarray<string,mixed>\|nullCode-block button settings (default: null).

Return:

self - The current response.



setHeader

Set an individual HTTP header.

public function setHeader(string $key, mixed $value): self

Parameters:

ParameterTypeDescription
$keystringThe header name.
$valuemixedThe header value for name.

Return:

Response - Return instance of the Response class.


setHeaders

Set multiple HTTP headers at once.

public function setHeaders(array $headers): self

Parameters:

ParameterTypeDescription
$headersarray<string,mixed>An associative array of headers key-pair.

Return:

Response - Return instance of the Response class.


sendStatus

Send the HTTP status code header with the corresponding status message.

This method also sends the Status header for compatibility with older clients.

public function sendStatus(): bool

Return:

bool - Returns true if the status header is valid and successfully sent, otherwise false.


send

Send HTTP response headers to the client.

Send the status and headers. Set $validate to true to enforce CORS checks.

public function send(bool $validate = false): void

Parameters:

ParameterTypeDescription
$validateboolWhether to apply APIs headers validations (default: false).

asFailed

Mark the response as failed.

When a response is marked failed:

  • Methods like output(), render(), json(), html(), etc., will return STATUS_ERROR instead of STATUS_SUCCESS or STATUS_SILENCE, even if content is empty or HTTP status is 204.
  • Essential for marking a failed middleware authentication, so routing system can terminate execution.
public function asFailed(bool $failed = true): self

Parameters:

ParameterTypeDescription
$failedboolWhether to mark the response as failed (default: true).

Return:

self - Return instance of response class.

Examples:

$response = (new Response())
    ->asFailed()
    ->setContent(['message']);

$response->output(); // Returns STATUS_ERROR

Note:Only use this method when handling middleware responses or when you want to explicitly return STATUS_ERROR.


render

Render and send response content along with optional headers.

  • Processes headers and content (minification, compression).
  • Sends headers and outputs the response body.

Configure compression or minification before calling this method. Headers already set on the response take precedence over the additional headers.

public function render(string $content, array $headers = []): int

Parameters:

ParameterTypeDescription
$contentstringThe response content to render.
$headersarray<string,mixed>Additional headers to send with the content..

Return:

int - Return the status code: STATUS_SUCCESS if successful, otherwise STATUS_ERROR.

Throws:

Luminova\Exceptions\ResponseException - If any error occur while rendering response.


setContent

Prepare the response body for later output. Arrays and objects are encoded as JSON. When the response has no content type, JSON input sets it to application/json.

Set the HTTP status, headers, and failure state before preparing content. Use getResult() to inspect the processed body or output() to send it.

public function setContent(string|array|object $content): self

Parameters:

ParameterTypeDescription
$contentstring\|array<int\|string,mixed>\|objectResponse body or data to encode as JSON.

Return:

self - The current response.

Throws:

Examples:

use Luminova\Template\Response;

$response = new Response(status: 201);
$response->setHeader('X-Request-Source', 'api');
$response->setContent(['created' => true]);

return $response;

output

Send the processed response to the client.

  • Outputs HTTP status, headers, and body generated by setContent().
  • Clears output buffers before sending content.
  • Optionally skips sending headers if they have already been sent.
public function output(bool $ifHeaderNotSent = true): int

Parameters:

ParameterTypeDescription
$ifHeaderNotSentboolIf true, headers are only sent if they have not already been sent (default: true).

Return:

int - STATUS_SUCCESS or STATUS_ERROR. An unprepared response returns STATUS_ERROR.


json

Send a JSON response.

public function json(
    array|object $content,
    int $flags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_BIGINT_AS_STRING
): int

Parameters:

ParameterTypeDescription
$contentarray<array-key, mixed>&#124;objectAn array or JSON object data to be encoded as JSON string.
$flagsintJSON encoding flags. Defaults to JSON_UNESCAPED_SLASHES \| JSON_UNESCAPED_UNICODE \| JSON_BIGINT_AS_STRING.

Return:

int - Return status code: STATUS_SUCCESS if successful, otherwise STATUS_ERROR.

Throws:

Luminova\Exceptions\JsonException - Throws if a JSON encoding error occurs.


text

Send a plain text response.

public function text(string $content): int

Parameters:

ParameterTypeDescription
$contentstringThe plain text content to render.

Return:

int - Return status code: STATUS_SUCCESS if successful, otherwise STATUS_ERROR.


html

Send an HTML response.

public function html(string $content): int

Parameters:

ParameterTypeDescription
$contentstringThe HTML content to render.

Return:

int - Return status code: STATUS_SUCCESS if successful, otherwise STATUS_ERROR.


xml

Send an XML response.

public function xml(string $content): int

Parameters:

ParameterTypeDescription
$contentstringThe XML content to render.

Return:

int - Return status code: STATUS_SUCCESS if successful, otherwise STATUS_ERROR.


download

Send a file or in-memory content as a download. Set any custom headers on the response before calling this method.

public function download(
    mixed $source,
    ?string $name = null,
    int $chunkSize = 8192,
    int $delay = 0
): bool

Parameters:

ParameterTypeDescription
$sourcemixedFile path or content accepted by the downloader.
$namestring\|nullDownload filename (default: null).
$chunkSizeintChunk size in bytes (default: 8192).
$delayintDelay between chunks in microseconds (default: 0).

Return:

bool - Whether the download succeeded.

Examples:

$response->download('/path/to/document.pdf', 'large-pdf.pdf');
$response->download('Hello world!', 'hello.txt');

stream

Send a readable file using the response headers. Optional ETag and expiry settings control client-side caching.

public function stream(
    string $filepath,
    bool $eTag = true,
    bool $weakEtag = false,
    int $expiry = 0,
    int $length = (1 << 21),
    int $delay = 0
): bool

Parameters:

ParameterTypeDescription
$filepathstringFull path to the file.
$eTagboolEnable ETag headers (default: true).
$weakEtagboolUse a weak ETag (default: false).
$expiryintCache duration in seconds (default: 0).
$lengthintChunk size in bytes (default: 1 << 21).
$delayintDelay between chunks in microseconds (default: 0).

Return:

bool - Whether the file was sent. Missing or unreadable files return false.

Examples:

$response->stream('/path/to/large-pdf.pdf', expiry: 3600);

See File Renderer for more options.


redirect

Send a redirect and terminate the request. Set the response status first to specify a status from 300 through 308. Otherwise, the method selects a status from the request method and protocol when available. It defaults to 302.

public function redirect(string $uri, bool $useRefresh = false): never

Parameters:

ParameterTypeDescription
$uristringRedirect destination.
$useRefreshboolSend a Refresh header (default: false). Microsoft IIS also uses Refresh automatically.

Return:

never - Terminates the request after sending the redirect.

Examples:

use Luminova\Template\Response;

(new Response(status: 303))->redirect('/orders');