HTTP Responses
Phexium provides a fluent ResponseBuilder for constructing PSR-7 HTTP responses with a clean, chainable API.
PSR-7 Compatibility
Phexium uses PSR-7 HTTP message interfaces (Psr\Http\Message\ServerRequestInterface and Psr\Http\Message\ResponseInterface) throughout its HTTP layer. The implementation is provided by the Nyholm/PSR7 library via the Slim framework, ensuring full interoperability with any PSR-7 compliant library.
Why Use ResponseBuilder
The builder pattern simplifies response construction by handling Content-Type headers automatically and providing a consistent interface across all controllers. Instead of manually writing to response bodies and setting headers, controllers use a declarative approach.
Usage
return $this->responseBuilder
->withResponse($response)
->withStatus(200)
->withHtml($html)
->build();
Available Methods
The ResponseBuilderInterface provides:
withResponse(ResponseInterface)- Set the base responsewithStatus(int)- Set HTTP status codewithHeader(string, string)- Replace a header valueaddHeader(string, string)- Append to existing headerwithHtml(string)- Set HTML body withtext/htmlContent-TypewithJson(array)- Set JSON body withapplication/jsonContent-Typebuild()- Return the final ResponseInterface
Response Patterns
HTML Response
$html = $this->twig->render('ListBooks.html.twig', (array) $viewModel);
return $this->responseBuilder
->withResponse($response)
->withHtml($html)
->build();
JSON Response
For direct JSON output:
return $this->responseBuilder
->withResponse($response)
->withJson(['id' => $bookId, 'status' => 'created'])
->withStatus(201)
->build();
API controllers extending AbstractApiController have helper methods:
return $this->jsonSuccess($response, $data); // 200 with data
return $this->jsonCreated($response); // 201
return $this->jsonError($response, 400, 'Error'); // Error with status
Redirect
return $this->responseBuilder
->withResponse($response)
->withStatus(302)
->withHeader('Location', '/books')
->build();
Custom Headers
return $this->responseBuilder
->withResponse($response)
->withHeader('X-Custom-Header', 'value')
->addHeader('Cache-Control', 'no-cache')
->addHeader('Cache-Control', 'no-store')
->withHtml($html)
->build();
Common Status Codes
| Code | Usage |
|---|---|
| 200 | Successful GET/display |
| 201 | Resource created (API) |
| 302 | Redirect after POST |
| 400 | Validation errors |
| 401 | Authentication required |
| 403 | Permission denied |
| 404 | Not found |
Source Files
src/Presentation/ResponseBuilderInterface.phpsrc/Presentation/ResponseBuilder.php
See Also
- Controllers - Response building in controllers
- PSR-7 HTTP Message Interface - Interface specification