
요청 (Request)
Slim 앱의 경로 및 미들웨어에는 웹 서버가 수신한 현재 HTTP 요청을 나타내는 PSR-7 요청 개체가 제공됩니다. 요청 개체는 HTTP 요청 메서드, 헤더 및 본문을 검사하고 조작할 수 있는 PSR-7 ServerRequestInterface를 구현합니다.
요청 헤더 (The Request Headers)
모든 HTTP 요청에는 헤더가 있습니다. 이것은 HTTP 요청을 기술하지만 요청 본문에 표시되지 않는 메타데이터입니다. Slim의 PSR-7 Request 객체는 헤더를 검사하는 여러 방법을 제공합니다.
모든 헤더 가져오기
모든 HTTP 요청 헤더를 PSR-7 Request 객체의 getHeaders()
메소드와 연관 배열로 가져올 수 있습니다. 결과적으로 반환된 연관 배열의 키는 헤더 이름이며, 그 값은 그 자체로 각각의 헤더 이름에 대한 문자열 값의 숫자 배열입니다.
$headers = $request->getHeaders();
foreach ($headers as $name => $values) {
echo $name . ": " . implode(", ", $values);
}
Figure 5: 모든 HTTP 요청 헤더를 연관 배열로 가져오고 반복합니다.
단일 헤더 가져오기
PSR-7 Request 객체의 getHeader($name)
메서드를 사용하여 단일 헤더의 값을 얻을 수 있습니다. 지정된 헤더 이름에 대한 값 배열을 반환합니다. 단일 HTTP 헤더는 둘 이상의 값을 가질 수 있습니다!
$headerValueArray = $request->getHeader('Accept');
Figure 6: Get values for a specific HTTP header.
You may also fetch a comma-separated string with all values for a given header with the PSR-7 Request object’s getHeaderLine($name)
method. Unlike the getHeader($name)
method, this method returns a comma-separated string.
$headerValueString = $request->getHeaderLine('Accept');
Figure 7: 특정 HTTP 헤더에 대한 값을 가져옵니다.
헤더 존재 여부 확인
PSR-7 Request 객체의 hasHeader($name)
방법으로 헤더의 존재 여부를 테스트할 수 있습니다.
if ($request->hasHeader('Accept')) {
// Do something
}
Figure 8: 특정 HTTP 요청 헤더의 존재를 탐지합니다.
요청 본문 (The Request Body)
모든 HTTP 요청에는 본문이 있습니다. JSON 또는 XML 데이터를 사용하는 Slim 애플리케이션을 구축하는 경우 PSR-7 Request 객체의 ‘GetParsedBody()’ 메소드를 사용하여 HTTP 요청 본문을 네이티브 PHP 형식으로 구문 분석할 수 있습니다. 본문 파싱은 PSR-7 구현마다 다릅니다.
설치한 PSR-7 구현에 따라 수신 입력을 구문 분석하기 위해 미들웨어를 구현해야 할 수도 있습니다. 다음은 들어오는 ‘JSON’ 입력을 구문 분석하는 예입니다.
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
class JsonBodyParserMiddleware implements MiddlewareInterface
{
public function process(Request $request, RequestHandler $handler): Response
{
$contentType = $request->getHeaderLine('Content-Type');
if (strstr($contentType, 'application/json')) {
$contents = json_decode(file_get_contents('php://input'), true);
if (json_last_error() === JSON_ERROR_NONE) {
$request = $request->withParsedBody($contents);
}
}
return $handler->handle($request);
}
}
$parsedBody = $request->getParsedBody();
Figure 9: HTTP 요청 본문을 네이티브 PHP 형식으로 구문 분석
기술적으로 말해서 PSR-7 Request 객체는 HTTP 요청 본문을 Psr\Http\Message\StreamInterface
의 인스턴스로 나타냅니다.HTTP 요청 본문 ‘StreamInterface’와 PSR-7 Request 객체의 ‘getBody()’ 메서드를 가져올 수 있습니다. 수신 HTTP 요청 크기를 알 수 없거나 사용 가능한 메모리에 비해 너무 큰 경우 ‘get Body()’ 메서드를 사용하는 것이 좋습니다.
$body = $request->getBody();
Figure 10: HTTP 요청 본문을 가져옴
결과적으로 ‘Psr’Http\Message\StreamInterface’ 인스턴스는 기본 PHP ‘리소스’를 읽고 반복할 수 있는 다음과 같은 메소드를 제공합니다.
- getSize()
- tell()
- eof()
- isSeekable()
- seek()
- rewind()
- isWritable()
- write($string)
- isReadable()
- read($length)
- getContents()
- getMetadata($key = null)