Response
A response is what the server sends to the browser: a status code, headers and a body. Normally an action returns a ViewModel, and the response is an HTML page. Sometimes something else is needed: send the visitor to another address, say that the page does not exist, or return data for JavaScript.
Redirect
After saving or deleting, the visitor is sent to another page. The redirect() plugin does that:
// module/Blog/src/Controller/PostController.php
public function deleteAction()
{
// the post will be deleted here
return $this->redirect()->toRoute('blog');
}Open /blog/delete/5 — the browser lands on /blog right away. The result of redirect() must be returned from the action.
| Call | Where it leads |
|---|---|
toRoute('blog') | To a route by name |
toRoute('blog/view', ['id' => 5]) | To a route with parameters |
toUrl('https://example.com') | To any address |
refresh() | To the same page |
The 404 error
The route /blog/999 exists, but a post with that number may not. Then the action reports that the page was not found:
public function viewAction()
{
$id = (int) $this->params()->fromRoute('id');
if ($id > 100) {
return $this->notFoundAction();
}
return new ViewModel(['id' => $id]);
}notFoundAction() sets the 404 code and shows the view script module/Application/view/error/404.phtml. The condition with the number 100 is temporary: once the database appears, this becomes a check of whether the post was found.
Status code and headers
The code and headers are changed through the response object:
$response = $this->getResponse();
$response->setStatusCode(403);
$response->getHeaders()->addHeaderLine('X-Robots-Tag', 'noindex');After that the action can return an ordinary ViewModel — the page is sent with the 403 code.
A JSON response
JSON is a text data format that JavaScript understands. First enable the JSON strategy in config/autoload/global.php:
// config/autoload/global.php
return [
'view_manager' => [
'strategies' => ['ViewJsonStrategy'],
],
];If the file already has other sections, add view_manager next to them. Now an action can return a JsonModel:
use Laminas\View\Model\JsonModel;
public function statusAction()
{
return new JsonModel([
'status' => 'ok',
'posts' => 2,
]);
}Add a route for the status action and open it: the browser shows {"status":"ok","posts":2}, and the Content-Type response header equals application/json. A JsonModel needs neither a view script nor a layout.
Common mistake
Calling $this->redirect()->toRoute('blog'); without return interrupts nothing: the action keeps running, and Laminas then looks for a view script and may show a page instead of redirecting. Always write return $this->redirect()->... — the same goes for notFoundAction().