Skip to content

Response objects

Greg Bowler edited this page Apr 24, 2026 · 2 revisions

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.

Create a response

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",
	])
);

Status code and reason phrase

$response = $response->withStatus(404);

echo $response->getStatusCode();  // 404
echo $response->getReasonPhrase(); // Not Found

The reason phrase is looked up from the built-in StatusCode mapping.

Headers

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().

Writing the body

The response body is a Stream, so the most direct pattern is:

$response->getBody()->write("Hello, world");

Convenience properties

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.

Redirect helpers

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.

Reading the body as different data types

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.

Clone this wiki locally