Luminova Framework

PHP Luminova: Custom Response Rendering

Last updated: 2025-05-08 06:53:34

The Response class lets you directly render or download content without using templates, giving you full control over what gets sent to the browser or client.

The Response class provides a simple and efficient way to render output from controller methods, routing callbacks, or any other part of your application where direct content delivery is needed.Unlike Template View Handling, which focuses on rendering template files from /resources/Views/ or HMVC paths like /app/Modules/?<Module>/Views/, the Response class allows you to stream or render raw content without extra overhead. This gives you full control over the output and improves performance, especially useful for APIs.

Key Features

  • Direct Rendering: Output raw or preprocessed content directly from controllers or route callbacks.
  • Global Access: Use the global helper function to access the Response instance without manual instantiation.

Limitations

  • No View Caching: Built-in caching is not supported. Use a custom caching solution if needed.
  • No Template Engine Support: Does not support rendering via Smarty, Twig, or other templating engines.

When to UseIdeal for rendering API responses or dynamic content where templating and view logic are unnecessary.


Class Definition


Usage

Initialization

Using the global helper function:

Returns a shared instance of the Response class.

$response = response(200);

Using direct instantiation:

use Luminova\Template\Response;

$response = new Response(200);

Render Content

Render custom content with headers:

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

Render JSON response:

$response->json([
    'message' => 'Foo bar'
]);

Render HTML content:

$response->html('<p>Foo bar</p>');

Stream or Download Files

Stream a file to the browser:

$response->stream('/path/to/file/', 'large-pdf.pdf', [
    'Content-Type' => 'application/pdf'
], true, 3600);

Download a file:

$response->download('/path/to/file/document.pdf', 'large-pdf.pdf', [
    'Content-Type' => 'application/pdf'
]);

Download raw content as a file:

$response->download('Hello world!', 'hello.txt', [
    'Content-Type' => 'text/plain'
]);

Methods

constructor

Initialize response class constructor with HTTP status code and optional headers.

function __construct(
    private int $status = 200, 
    private array $headers = [],
    private bool $compress = false,
    private bool $minifyCodeblocks = false,
    private bool $codeblockButton = false
)

Parameters:

ParameterTypeDescription
$statusintHTTP status code (default: 200 OK).
$headersarray<string,mixed>Optional HTTP headers as key-value pairs.
$compressboolWhether to apply content compression (e.g., gzip, deflate), default is false.
$minifyCodeblocksboolWhether to exclude HTML code blocks from minification (default: false).
$codeblockButtonboolWhether to automatically add a copy button to code blocks after minification (default: false).

getStatusCode

Get the current HTTP status code.

public getStatusCode(): int

Return Value:

int - Return the current HTTP status code.


getHeaders

Retrieve all set HTTP headers.

public getHeaders(): array<string,mixed>

Return Value:

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


getHeader

Retrieve the value of a specific HTTP header.

public getHeader(string $name): mixed

Parameters:

ParameterTypeDescription
$namestringThe name of the header.

Return Value:

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


getProtocolVersion

Get the HTTP protocol version being used (e.g., 1.0, 1.1).

public getProtocolVersion(): float

Return Value:

float - Return the HTTP protocol version.


clearHeaders

Clear all previously set HTTP headers.

public clearHeaders(): void

clearRedirects

Clear any redirects set in the response headers.

public clearRedirects(): bool

Return Value:

bool - Return true if any redirects were cleared, false otherwise.


hasRedirects

Check if the response headers contain any redirects.

public hasRedirects(): bool

Return Value:

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


setStatus

Set the HTTP status code for the response.

public setStatus(int $status): self

Parameters:

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

Return Value:

Response - Return instance of the Response class.


compress

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

public compress(bool $compress = true): self;

Parameters:

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

Return Value:

Response - Return instance of the Response class.


minify

Enable or disable HTML content minification.

Set enable or disable HTML content minification, otherwise it will use default flag in env file page.minification.

public minify(bool $minify = true): self

Parameters:

ParameterTypeDescription
$minifyboolWhether to minify the HTML content (default: true).

Return Value:

Response - Return instance of the Response class.

This overrides the environment variable page.minification.


codeblock

Configure minification behavior for HTML code blocks and optional copy button.

Set if HTML codeblock tags should be ignore during content minification.For this to work correctly minification of content must be enabled either by calling method minify or enabling minification in env file.

public codeblock(bool $minify, bool $button = false): self 

Parameters:

ParameterTypeDescription
$minifyboolWhether to exclude HTML code blocks from minification (default: false).
$buttonboolWhether to include a copy button in code blocks (default: false).

Return Value:

Response - Return instance of the Response class.


header

Set an individual HTTP header.

public header(string $key, mixed $value): self 

Parameters:

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

Return Value:

Response - Return instance of the Response class.


headers

Set multiple HTTP headers at once.

public headers(array<string,mixed> $headers): self 

Parameters:

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

Return Value:

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 sendStatus(): bool 

Return Value:

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


send

Send HTTP response headers to the client.

Send all response headers and the status code to the client without content body. Optionally validate the against REST Api headers based on App\Config\Apis if $validate is set to true.

public send(bool $validate = false): void 

Parameters:

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

render

Render and output any type response content along with additional optional headers.

Using this method allows you to pass encode or minify without using the default from env.

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

Parameters:

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

Return Value:

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

Note: The default content type is application/json if non was provided in $headers.


json

Send a JSON response.

public json(array|object $content): int

Parameters:

ParameterTypeDescription
$contentarray|objectAn array or JSON object data to be encoded as JSON string.

Return Value:

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 text(string $content): int

Parameters:

ParameterTypeDescription
$contentstringThe plain text content to render.

Return Value:

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


html

Send an HTML response.

public html(string $content): int

Parameters:

ParameterTypeDescription
$contentstringThe HTML content to render.

Return Value:

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


xml

Send an XML response.

public xml(string $content): int

Parameters:

ParameterTypeDescription
$contentstringThe XML content to render.

Return Value:

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


download

Send a file or content as a browser download.

public download(
    string $fileOrContent, 
    ?string $name = null, 
    array $headers = [],
    int $chunkSize = 8192,
    int $delay = 0
): bool

Parameters:

ParameterTypeDescription
$pathstringPath to the file or content to be downloaded.
$namestring|nullOptional name to be used for the downloaded file.
$headersarrayOptional download headers.
$chunkSizeintThe size of each chunk in bytes for large content (default: 8192, 8KB).
$delayintThe delay between each chunk in microseconds (default: 0).

Return Value:

bool - Return true if the download was successful, false otherwise.


stream

Stream output any file or large files to the client.

public stream(
    string $path, 
    string $basename, 
    array $headers = [], 
    bool $eTag = true, 
    bool $weakEtag = false,
    int $expiry = 0,
    int $length = (1 << 21),
    int $delay = 0
): bool

Parameters:

ParameterTypeDescription
$pathstringThe path to file storage (e.g: /writeable/storages/images/).
$namestringThe file name (e.g., image.png).
$headersarrayOptional stream output headers.
$eTagboolWhether to generate ETag headers (default: true).
$weakEtagboolWhether to use a weak ETag header or string (default: false).
$expiryintExpiry time in seconds for cache control (default: 0), indicating no cache.
$lengthintOptional size of each chunk to be read (default: 2MB).
$delayintOptional delay in microseconds between chunk length (default: 0).

Return Value:

bool - Return true if file streaming was successful, false otherwise.

See:

Private File Delivery Manager - For more information and advanced usage.


redirect

Redirect the client to a new URL.

Redirect the client to a different URI location with the appropriate status code (302, 303, or 307) .This method handles HTTP redirection by sending an appropriate Location or Refresh header and optionally specifying a status code. It auto-detects IIS environments and uses the refresh method for compatibility.

public redirect(string $uri, ?string $method = null, ?int $code = null): void

Parameters:

ParameterTypeDescription
$uristringThe target URI for the redirection.
$methodstring|nullOptional. The redirection method (refresh or null for standard).
$codeint|nullOptional HTTP status code (e.g., 302, 303, 307).

Note: If $code is set to null, it will try detecting status code based on request method and protocol version.