Response
General flow
In most scenarios, you won't interact with the Response class directly after your defaults have been set up.
The Response class
The Response class is used by internal processes to handle the http-answer. When the last class implementing Routable in your logic chain returns, the Route class automatically passes the accumulated results to the output defined in the current route or based on your settings. Like any other part of LENKRAD, the process is fully exposed to you. The Response class offers the following static methods:
setDefaultOutput(ResponseOutput $output)
Takes a Neoan\Enums\ResponseOutput case. The default is ResponseOutput::JSON
output($data, array $renderOptions)
Manually triggers immediate output with given specifications
getDefaultOutput()
Returns default Neoan\Enums\ResponseOutput case
setDefaultRenderer(string $renderer)
Expects classname of class implementing Neoan\Render\RenderEngine. (You can set alternative Renderers at a route-level as well)
json(Serializable $data)
Serializes provided data to json and responds immediately (with corresponding header). Method gets called internally if defaultOutput is set to ResponseOutput::JSON
html(mixed $data, ?string $view)
Normalizes $data (DataNormalization instance), applies it to provided view and immediately responds with output. Method gets called internally if defaultOutput is set to ResponseOutput::HTML
setStatuscode(int $httpResponseCode)
Sets response code in response header.
redirect(string $whereTo)
Redirects to specified location and stops execution.
getInstance(?ResponseInterface = null)
Returns Response instance. A mock response can be passed in (for testing)
detachInstance()
Resets singleton instance.
Setting defaults
If you are routing by attributes, there are no default settings you need to worry about regarding the response. If you define your routes classically, you might want to simplify your route definitions by setting a default for the most common case of route.
Server Side Rendered Application
If your routes tend to be rendered pages, consider
use Neoan\Response\Response;
use Neoan\Enums\ResponseOutput;
Response::setDefaultOutput(ResponseOutput::HTML)
JSON API
If you are building a pure backend, consider
use Neoan\Response\Response;
use Neoan\Enums\ResponseOutput;
Response::setDefaultOutput(ResponseOutput::JSON);
You can always overwrite the response-type on the route level.
Programmatic example
use Neoan\Response\Response;
use Neoan\Request\Request;
use Neoan\Enums\ResponseOutput;
// In a monolith, we might have api-routes and web-routes
$isApi = str_starts_with(Request::getRequestUri(), '/api/');
Response::setDefaultOutput($isApi ? ResponseOutput::JSON : ResponseOutput::HTML);
Before you move on
Many references on this page assume default settings. Your project might differ in behavior, paths etc.