PHP Luminova: Custom Response Rendering
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
- Class namespace:
\Luminova\Template\Response
- This class implements \Luminova\Interface\ViewResponseInterface
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:
Parameter | Type | Description |
---|---|---|
$status | int | HTTP status code (default: 200 OK ). |
$headers | array<string,mixed> | Optional HTTP headers as key-value pairs. |
$compress | bool | Whether to apply content compression (e.g., gzip , deflate ), default is false. |
$minifyCodeblocks | bool | Whether to exclude HTML code blocks from minification (default: false). |
$codeblockButton | bool | Whether 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:
Parameter | Type | Description |
---|---|---|
$name | string | The 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:
Parameter | Type | Description |
---|---|---|
$status | int | The 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:
Parameter | Type | Description |
---|---|---|
$encode | bool | Whether 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:
Parameter | Type | Description |
---|---|---|
$minify | bool | Whether 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 correctlyminification
of content must be enabled either by calling methodminify
or enabling minification inenv
file.
public codeblock(bool $minify, bool $button = false): self
Parameters:
Parameter | Type | Description |
---|---|---|
$minify | bool | Whether to exclude HTML code blocks from minification (default: false). |
$button | bool | Whether 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:
Parameter | Type | Description |
---|---|---|
$key | string | The header name. |
$value | mixed | The 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:
Parameter | Type | Description |
---|---|---|
$headers | array<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:
Parameter | Type | Description |
---|---|---|
$validate | bool | Whether 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:
Parameter | Type | Description |
---|---|---|
$content | string | The response content to render. |
$headers | array<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:
Parameter | Type | Description |
---|---|---|
$content | array|object | An 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:
Parameter | Type | Description |
---|---|---|
$content | string | The 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:
Parameter | Type | Description |
---|---|---|
$content | string | The 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:
Parameter | Type | Description |
---|---|---|
$content | string | The 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:
Parameter | Type | Description |
---|---|---|
$path | string | Path to the file or content to be downloaded. |
$name | string|null | Optional name to be used for the downloaded file. |
$headers | array | Optional download headers. |
$chunkSize | int | The size of each chunk in bytes for large content (default: 8192, 8KB). |
$delay | int | The 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:
Parameter | Type | Description |
---|---|---|
$path | string | The path to file storage (e.g: /writeable/storages/images/ ). |
$name | string | The file name (e.g., image.png ). |
$headers | array | Optional stream output headers. |
$eTag | bool | Whether to generate ETag headers (default: true ). |
$weakEtag | bool | Whether to use a weak ETag header or string (default: false ). |
$expiry | int | Expiry time in seconds for cache control (default: 0), indicating no cache. |
$length | int | Optional size of each chunk to be read (default: 2MB). |
$delay | int | Optional 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:
Parameter | Type | Description |
---|---|---|
$uri | string | The target URI for the redirection. |
$method | string|null | Optional. The redirection method (refresh or null for standard). |
$code | int|null | Optional HTTP status code (e.g., 302 , 303 , 307 ). |
Note: If
$code
is set tonull
, it will try detecting status code based on request method and protocol version.