Awilum
August 31, 2021, 4:44pm
1
use Slim\Psr7\Response as R;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
/**
* Login page
*
* @param Request $request ServerRequestInterface
* @param Response $response ResponseInterface.
*/
public function login(Request $request, Response $response): Response
{
$r = new R();
$r->withHeader('Location', 'http://localhost');
dump($r);
dd($r->getHeaders());
...
}
^ Slim\Psr7\Response {#423 ▼
#status: 200
#reasonPhrase: ""
#protocolVersion: "1.1"
#headers: Slim\Psr7\Headers {#424 ▼
#globals: []
#headers: []
}
#body: Slim\Psr7\Stream {#425 ▼
#stream: stream resource @508 ▶}
#meta: null
#readable: null
#writable: null
#seekable: null
#size: null
#isPipe: null
#finished: false
#cache: null
}
}
[]
Why headers are empty for new response ?
Real code example, is that I am using redirect() helper inside method login() and it is not works because new response headers are empty for some reason.
"slim/slim": "^4.8.1",
"slim/psr7": "^1.4",
function redirect(string $routeName, array $data = [], array $queryParams = []): Response
{
$response = new Response();
$response->withHeader('Location', urlFor($routeName, $data, $queryParams));
return $response;
}
Awilum
August 31, 2021, 6:02pm
2
function redirect(string $routeName, array $data = [], array $queryParams = []): Response
{
$response = new Response();
$response->withHeader('Location', urlFor($routeName, $data, $queryParams));
$response->getBody()->write("Hello");
return $response;
}
Added for test and it works
$response->getBody()->write("Hello");
but $response->withHeader
is not.
odan
August 31, 2021, 7:40pm
3
The headers are immutable. This should work:
$response = $response->withHeader('Location', 'new url');
1 Like
Awilum
September 1, 2021, 5:01am
4
Thanks! it is works
but does this correct here:
/**
* {@inheritdoc}
*/
public function redirect(string $from, $to, int $status = 302): RouteInterface
{
$responseFactory = $this->responseFactory;
$handler = function () use ($to, $status, $responseFactory) {
$response = $responseFactory->createResponse($status);
return $response->withHeader('Location', (string) $to);
};
return $this->get($from, $handler);
}
}
odan
September 1, 2021, 6:04am
5
Yes this is also correct in this context. It just returns the new instance directly.