-
-
Notifications
You must be signed in to change notification settings - Fork 0
Response objects
GT\Http\Response represents the HTTP response your application will send back.
At the PSR-7 level, a response is mostly:
- a status code
- a set of headers
- a body stream
This implementation also adds a few convenience helpers such as ok, status, statusText, type, redirect helpers, and body conversion helpers.
use GT\Http\Response;
$response = new Response();You can also pass a status code and headers up front:
use GT\Http\Header\ResponseHeaders;
$response = new Response(
200,
new ResponseHeaders([
"Content-Type" => "text/plain; charset=UTF-8",
])
);$response = $response->withStatus(404);
echo $response->getStatusCode(); // 404
echo $response->getReasonPhrase(); // Not FoundThe reason phrase is looked up from the built-in StatusCode mapping.
Headers work through the shared message API:
$response = $response
->withHeader("Content-Type", "application/json")
->withAddedHeader("Cache-Control", "no-store");The response also exposes a typed ResponseHeaders object through $response->headers and getResponseHeaders().
The response body is a Stream, so the most direct pattern is:
$response->getBody()->write("Hello, world");The response exposes a few readable helper properties:
$response->ok$response->status$response->statusText$response->type$response->uri$response->url
The uri and url helpers are mainly useful when the response came from phpgt/fetch, where they reflect the effective response URL in a browser-style way.
Response includes redirect(), reload(), and reloadWithoutQuery().
$response->redirect("/login", 303);Calling redirect() sets the Location header and updates the status code. A debug header is also added so the redirect source can be traced more easily during development.
If the response body contains text that should be interpreted in a different format, helper methods are available:
-
text()/awaitText() -
json()/awaitJson() -
blob()/awaitBlob() -
arrayBuffer()/awaitArrayBuffer() -
formData()/awaitFormData()
$json = $response->awaitJson();
$text = $response->awaitText();These helpers are most natural when Response objects come from phpgt/fetch, but they also work with already-populated response bodies.
Note
In WebEngine, page logic will manipulate a Response object rather than returning or echoing plain strings. The framework then sends the response headers and stream body to the browser at the end of the request lifecycle.
URI objects provide a structured way to work with locations and resource identifiers in HTTP.
PHP.GT/Http is a separately maintained component of PHP.GT/WebEngine.
- Creating requests from global state
- Request and ServerRequest objects
- Response objects
- URI objects
- Working with headers
- Parts of the HTTP header