Responds
Raxos\Router\Responds is a trait for controllers and middleware. It adds short protected helper methods for building common HttpResponse instances. Use it with use Responds; inside your class.
trait Responds
{
// ...
}Methods
json
protected function json(mixed $body, HttpHeadersMap $headers = new HttpHeadersMap(), HttpResponseCode $responseCode = HttpResponseCode::OK): HttpResponseReturns a JSON response.
html
protected function html(string $body, HttpHeadersMap $headers = new HttpHeadersMap(), HttpResponseCode $responseCode = HttpResponseCode::OK): HttpResponseReturns an HTML response.
result
protected function result(mixed $result, HttpHeadersMap $headers = new HttpHeadersMap(), HttpResponseCode $responseCode = HttpResponseCode::OK): HttpResponseReturns a generic result response, the same wrapper the router applies automatically to non-HttpResponse return values.
redirect
protected function redirect(string $destination, HttpHeadersMap $headers = new HttpHeadersMap(), HttpResponseCode $responseCode = HttpResponseCode::FOUND): HttpResponseReturns a redirect response, defaulting to status 302 Found.
file
protected function file(string $path, HttpRequest $request, HttpHeadersMap $headers = new HttpHeadersMap()): HttpResponseReturns a file response for the given path, honoring conditional request headers.
binary
protected function binary(string $data, HttpHeadersMap $headers = new HttpHeadersMap()): HttpResponseReturns a raw binary response.
noContent
protected function noContent(HttpHeadersMap $headers = new HttpHeadersMap()): HttpResponseReturns a 204 No Content response.
notFound
protected function notFound(): HttpResponseReturns a 404 Not Found response.
forbidden
protected function forbidden(HttpHeadersMap $headers = new HttpHeadersMap()): HttpResponseReturns a 403 Forbidden response.
error
protected function error(Throwable&JsonSerializable $err): HttpResponseReturns a JSON error response for a JSON-serializable exception, using its responseCode property when present.
validationError
protected function validationError(string $field, string $constraint, string $message, array $params = []): HttpResponseReturns a JSON validation error response for a single field and constraint.
validationErrors
protected function validationErrors(array ...$errors): HttpResponseReturns a JSON validation error response for multiple fields and constraints at once.
Example
<?php
declare(strict_types=1);
namespace App\Http\Controller;
use Raxos\Router\Attribute\{Controller, Get};
use Raxos\Router\Responds;
#[Controller('/todos')]
final readonly class TodoController
{
use Responds;
#[Get('/')]
public function index(): mixed
{
return $this->json(['todos' => []]);
}
}See Building responses for more.