Requests and Responses

Derafu\Http\Request and Derafu\Http\Response wrap PSR-7 messages and add shortcuts for the things an application does all the time: reading input, negotiating the format and building common responses.

They are immutable

As PSR-7 says, a message does not change: every withX() method returns a new instance and the original stays as it was. Keep the result: $response = $response->withHeader('X-A', 'a');.

Request

Request implements PSR-7’s ServerRequestInterface, so everything from PSR-7 is available. It is created by RequestFactoryMiddleware, which means a handler or any middleware after it receives a Derafu\Http\Request.

Reading input

$id = $request->query('id', 0);              // From the query string.
$name = $request->post('name');              // From the parsed body (form).
$token = $request->header('X-Token', '');    // First value of a header.

if ($request->isJson()) {
    $data = $request->json();                // Decoded array, or null.
}

$all = $request->all();
$email = $request->input('email', '');
$some = $request->only(['name', 'email']);
Method Returns
query($key, $default) A value from the query string
post($key, $default) A value from the parsed body, or the default when the body is not an array
header($name, $default) The first value of a header, or the default
isJson() Whether Content-Type contains application/json
json() The decoded JSON body as an array, or null when the request is not JSON, the body is invalid, or it does not decode to an array
all() Query, parsed body and JSON body merged, in that order, using PHP’s array_merge() semantics
input($key, $default) A value from all()
only($keys) The given keys from all()

JSON lists and numeric parameter names are supported. In all(), later sources replace earlier values with the same string key; numeric keys are appended and renumbered by array_merge(). only() preserves the selected keys from that result. PSR-7 attributes and server parameters also retain their PHP array keys: a string attribute name such as '123' appears as an integer key in getAttributes() and remains accessible with getAttribute('123').

Files

if ($request->hasFile('document')) {
    $file = $request->file('document');   // PSR-7 UploadedFileInterface.
}
$files = $request->files();

hasFile() is true only when the file was uploaded without error. file() returns null when there is no such file.

Application context

Method Returns
route() The RouteMatchInterface stored by RouterMiddleware
session() The session, stored by the session middleware
flash() The flash messages, stored by the flash middleware
user() The authenticated user, or null

route(), session() and flash() throw a LogicException when the middleware that provides them did not run before. user() never throws.

Content negotiation

The request decides which format the client wants, and the response, errors included, follow it. getPreferredContentType() checks, in this order:

  1. The extension in the URL: /report.json means JSON, /page.html means HTML.
  2. Whether it is an API request, that is the path is /api or starts with /api/: JSON.
  3. Whether it is an XHR request (X-Requested-With: XMLHttpRequest): JSON.
  4. The Accept header, ordered by its q values. The first of application/json, text/html, text/plain, text/markdown or application/pdf that appears wins.
  5. HTML, when there is no Accept header or none of those is in it.

getPreferredFormat() returns the same as a subtype string (json, html, …). isApiRequest() and isXmlHttpRequest() expose the individual checks.

The app variable in templates

A Twig template has the variable app, the same in every template, with what it needs to know about the request that is being handled:

In the template What it is
app.request The Request
app.route The RouteMatchInterface that matched, or null
app.user The authenticated user, or null when nobody is (an anonymous user is nobody, so {% if app.user %} works)
app.session The session, or null
app.flashes The flash messages of the request, by type. Reading them does not take them away
{% if app.user %}
    Hello, {{ app.user.identity }}.
{% endif %}

What is not there yet (no route, no session, an error before the user is known) is null, not an error. The variable is given by Derafu\Http\Twig\AppExtension, which derafu/foundation adds to the renderer; a site that builds its own renderer adds @Derafu\Http\Twig\AppExtension to its extensions. app has the request that the Dispatcher is dispatching, the one of the controller or of the error page that is being rendered (Derafu\Http\Contract\RequestStackInterface keeps the requests of the dispatches that are running): outside of a dispatch, app.request is null.

Response

use Derafu\Http\Enum\HttpStatus;
use Derafu\Http\Response;

return (new Response())
    ->asJson(['id' => 42])
    ->withHttpStatus(HttpStatus::CREATED);
Method What it does
asJson($data, $flags) JSON body with Content-Type: application/json. Throws a JsonException if the data can not be encoded. The default flags do not escape slashes or unicode
asText($data, $type) Text body; $type is a ContentType, ContentType::PLAIN by default
asHtml($html) HTML body
redirect($url, $status) Location header and empty body. HttpStatus::FOUND (302) by default
asDownload($source, $filename, $type, $deleteAfter) A file that the client saves, of any size. See Downloads
withHttpStatus($status) Sets the status code and reason phrase from an HttpStatus
withContentType($type) Sets Content-Type, adding charset=UTF-8 to text types

Downloads

asDownload() makes the response of a file that the client saves. The body is never read into memory: the Runtime sends it in pieces, so a file of hundreds of megabytes costs the same memory as one of a few kilobytes.

use Derafu\Http\Enum\ContentType;
use Derafu\Http\Response;

// Content that is already in memory (small).
return (new Response())->asDownload($csv, 'sales.csv', ContentType::CSV);

// A file on disk: the name is the one of the file unless another is given.
return (new Response())->asDownload(new SplFileInfo($path), type: ContentType::PDF);

// A temporary file: it is deleted as soon as it is open to be sent.
return (new Response())->asDownload(new SplFileInfo($tmp), 'report.zip', ContentType::ZIP, deleteAfter: true);
$source What is sent
string The content. A string is never a path, so a name that comes from a user can not open a file
StreamInterface or stream resource The stream, as it is
SplFileInfo The file, opened for reading. A file that does not exist, is a directory or can not be read is an error

Any other type is an InvalidArgumentException that names the type received.

What the response has:

  • Content-Type of $type (application/octet-stream by default) and Content-Disposition: attachment, with the name of the file only when there is one.
  • Content-Length when the stream knows its size, and Accept-Ranges: bytes when it can also be moved to any position, so the client can resume the download or ask for a part (see Ranges). A stream of unknown size has neither and is sent as it is read.
  • The name of the file is whatever the caller has, so it can not break the header: control characters, quotes, slashes and backslashes are replaced. The name in ASCII goes in filename, and when it has other characters the real one goes in filename* (RFC 6266). A name that is not UTF-8 is read as ISO-8859-1. An empty name is download.

$deleteAfter is only for a file as the source (with another one it is an error). The file is opened and then deleted, and the open stream keeps it readable while it is sent, so a temporary file stays nowhere whatever happens afterwards.

Returning data instead of a response

A handler does not have to build a Response. If it returns an array, a string or an object, ResponseNormalizerMiddleware turns it into one using the preferred content type of the request. See Middleware.

public function show(string $id): array
{
    // Sent as JSON to an API client.
    return ['id' => $id];
}

Build the Response yourself when you need control over the status or the headers.

Enums

ContentType

Derafu\Http\Enum\ContentType lists the media types the library knows. Besides its value (the media type string) it provides:

Method Purpose
fromFilename($name), fromExtension($ext) Find the type from a file name or extension; OCTET_STREAM when unknown
withCharset($charset) The media type with ; charset=... appended
getMainType(), getSubType() application and json for application/json
isText(), isImage(), isAudio(), isVideo(), isFont() Group checks
isStatic() Whether it is a known file type: everything except OCTET_STREAM. It is what StaticFilesMiddleware uses

HttpStatus

Derafu\Http\Enum\HttpStatus has a case for each status code, for example HttpStatus::NOT_FOUND. It provides getReasonPhrase() and the checks isInformational(), isSuccessful(), isRedirection(), isClientError(), isServerError() and isError().

On this page

Last updated on 15/11/2026 by Anonymous