PHP Luminova: View Response Object
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
Responseinstance using a global helper — no need tonewit 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
SmartyorTwig.
Note:
This class does not behave like
Luminova\Http\Message\Responseand it does not implementPsr\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
- Full namespace:
Luminova\Template\Response - This class implements Luminova\Interface\ContentResponseInterface.
- This class is final.
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:
| Parameter | Type | Description |
|---|---|---|
$content | string\|array<int\|string,mixed>\|object\|null | Content to process immediately (default null). |
$status | int | HTTP status code (default 200). |
$headers | array<string, mixed> | Response headers keyed by name (default []). |
$compress | bool | Enable response compression (default false). |
$minify | bool | Enable HTML minification (default false). |
$preserveTags | string[]|null | HTML 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(): intReturn:
int - Return the current HTTP status code.
getHeaders
Retrieve all set HTTP headers.
public function getHeaders(): arrayReturn:
array<string,mixed> - Return an array of all headers.
getHeader
Retrieve the value of a specific HTTP header.
public function getHeader(string $name): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The 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(): arrayReturn:
array<string,mixed> - Processed response data.
| Key | Type | Description |
|---|---|---|
exit | int | Framework exit status. |
status | int | HTTP status at the time the content was prepared. |
headers | array<string,mixed> | Prepared response headers. |
contents | string | Processed 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(): voidclearRedirects
Clear any redirects set in the response headers.
public function clearRedirects(): voidReturn:
void - Clears redirect headers from the response.
hasRedirects
Check if the response headers contain any redirects.
public function hasRedirects(): boolReturn:
bool - Return true if redirects are set, false otherwise.
setStatus
Set the HTTP status code for the response.
public function setStatus(int $status): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$status | int | The 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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$compress | bool | Whether 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
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$minify | bool | Enable HTML minification (default: true). |
$preserveTags | array<int,string>\|null | Tags whose contents should be preserved (default: null). |
$codeBlockButtons | array<string,mixed>\|null | Code-block button settings (default: null). |
Return:
self - The current response.
setHeader
Set an individual HTTP header.
public function setHeader(string $key, mixed $value): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The header name. |
$value | mixed | The header value for name. |
Return:
Response - Return instance of the Response class.
setHeaders
Set multiple HTTP headers at once.
public function setHeaders(array $headers): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$headers | array<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
Statusheader for compatibility with older clients.
public function sendStatus(): boolReturn:
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): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$validate | bool | Whether 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 returnSTATUS_ERRORinstead ofSTATUS_SUCCESSorSTATUS_SILENCE, even if content is empty or HTTP status is204. - Essential for marking a failed middleware authentication, so routing system can terminate execution.
public function asFailed(bool $failed = true): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$failed | bool | Whether 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_ERRORNote: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 = []): intParameters:
| Parameter | Type | Description |
|---|---|---|
$content | string | The response content to render. |
$headers | array<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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$content | string\|array<int\|string,mixed>\|object | Response body or data to encode as JSON. |
Return:
self - The current response.
Throws:
- Luminova\Exceptions\JsonException If JSON encoding fails.
- Luminova\Exceptions\ResponseException If response processing fails.
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): intParameters:
| Parameter | Type | Description |
|---|---|---|
$ifHeaderNotSent | bool | If 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
): intParameters:
| Parameter | Type | Description |
|---|---|---|
$content | array<array-key, mixed>|object | An array or JSON object data to be encoded as JSON string. |
$flags | int | JSON 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): intParameters:
| Parameter | Type | Description |
|---|---|---|
$content | string | The 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): intParameters:
| Parameter | Type | Description |
|---|---|---|
$content | string | The 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): intParameters:
| Parameter | Type | Description |
|---|---|---|
$content | string | The 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
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$source | mixed | File path or content accepted by the downloader. |
$name | string\|null | Download filename (default: null). |
$chunkSize | int | Chunk size in bytes (default: 8192). |
$delay | int | Delay 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
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$filepath | string | Full path to the file. |
$eTag | bool | Enable ETag headers (default: true). |
$weakEtag | bool | Use a weak ETag (default: false). |
$expiry | int | Cache duration in seconds (default: 0). |
$length | int | Chunk size in bytes (default: 1 << 21). |
$delay | int | Delay 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): neverParameters:
| Parameter | Type | Description |
|---|---|---|
$uri | string | Redirect destination. |
$useRefresh | bool | Send 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');