HTTP Responses
All Template and Custom Route controllers should return a PSR7 compliant response to be sent back to the user's browser.
Views and Strings
If your Controller returns a string or a view it will be automatically converted to an HtmlResponse object with a 200 status code.
Arrays and Iterables
If your Controller returns an array or an iterable object it will be automatically converted to a JsonResponse object with a 200 status code.
Diactoros Reponses
For all other response types, you have access to Laminas/Diactoros.
// Check out the Diactoros documentation for further details and examples:
// https://docs.laminas.dev/laminas-diactoros/v2/custom-responses/
$response = new Laminas\Diactoros\Response\TextResponse('Hello world!');
$response = new Laminas\Diactoros\Response\HtmlResponse($htmlContent);
$response = new Laminas\Diactoros\Response\XmlResponse($xml);
$response = new Laminas\Diactoros\Response\JsonResponse($data);
$response = new Laminas\Diactoros\Response\EmptyResponse(); // Basic 204 response:
$response = new Laminas\Diactoros\Response\RedirectResponse('/user/login', 301); // redirect
Adding status code & headers
One of the benefits of using Response Objects is that they make it easier to control the HTTP status code & headers. Diactoros responses let you set both the status code and headers in their constructor.
use Laminas\Diactoros\Response\JsonResponse;
return new JsonResponse($data, 422, ['X-Total-Validation-Errors' => 2]);
Or if you prefer, you can use the withStatus and withHeader methods instead.
use Laminas\Diactoros\Response\JsonResponse;
return (new JsonResponse($data, 422))
->withStatus(422)
->withHeader('X-Total-Validation-Errors', 2);
TODO
Add an easier Laravel style shortcut to produce responses.