
요청 (Request)
Slim 앱의 경로 및 미들웨어에는 웹 서버가 수신한 현재 HTTP 요청을 나타내는 PSR-7 요청 개체가 제공됩니다. 요청 개체는 HTTP 요청 메서드, 헤더 및 본문을 검사하고 조작할 수 있는 PSR-7 ServerRequestInterface를 구현합니다.
요청 개체를 가져오는 방법
PSR-7 요청 객체는 다음과 같이 경로 콜백에 대한 첫 번째 인수로 Slim 애플리케이션 경로에 주입됩니다.
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$app->get('/hello', function (Request $request, Response $response) {
$response->getBody()->write('Hello World');
return $response;
});
$app->run();
Figure 1: 응용 프로그램 경로 콜백에 PSR-7 요청 주입
PSR-7 요청 객체는 다음과 같이 호출 가능한 미들웨어의 첫 번째 인수로 Slim 애플리케이션 미들웨어에 주입됩니다.
<?php
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$app->add(function (Request $request, RequestHandler $handler) {
return $handler->handle($request);
});
// ...define app routes...
$app->run();
Figure 2: 응용 프로그램 미들웨어에 PSR-7 요청을 삽입합니다.
요청 메소드 (The Request Method)
모든 HTTP 요청에는 일반적으로 다음 중 하나의 메서드가 있습니다.
- GET
- POST
- PUT
- DELETE
- HEAD
- PATCH
- OPTIONS
HTTP 요청의 메소드는 ‘getMethod()’라는 적절한 이름의 Request object 메소드를 사용하여 검사할 수 있습니다.
$method = $request->getMethod();
HTTP 요청 메서드를 위조하거나 재지정할 수 있습니다. 예를 들어 ‘GET’ 또는 ‘POST’ 요청만 지원하는 기존 웹 브라우저를 사용하여 ‘PUT’ 요청을 모방해야 할 경우 유용합니다.
주의점!
Method Overriding Middleware를 재정의하는 요청 방법이 당신의 어플리케이션에 주입되어야 한다.
HTTP 요청 메서드를 재정의하는 두 가지 방법이 있습니다. POST 요청 본문에 ‘Method’ 매개 변수를 포함할 수 있습니다. HTTP 요청에서는 ‘응용 프로그램/x-ww-form-urlencoded’ 콘텐츠 유형을 사용해야 합니다.
POST /path HTTP/1.1
Host: example.com
Content-type: application/x-www-form-urlencoded
Content-length: 22
data=value&_METHOD=PUT
Figure 3: Override HTTP method with _METHOD parameter.
You can also override the HTTP request method with a custom X-Http-Method-Override
HTTP request header. This works with any HTTP request content type.
POST /path HTTP/1.1
Host: example.com
Content-type: application/json
Content-length: 16
X-Http-Method-Override: PUT
{"data":"value"}
Figure 4: HTTP 메서드를 _Method 매개 변수로 재정의합니다.
요청 URI (The Request URI)
모든 HTTP 요청에는 요청된 응용 프로그램 리소스를 식별하는 URI가 있습니다. HTTP 요청 URI는 다음과 같은 여러 부분으로 구성되어 있습니다.
- Scheme (e.g.
http
orhttps
) - Host (e.g.
example.com
) - Port (e.g.
80
or443
) - Path (e.g.
/users/1
) - Query string (e.g.
sort=created&dir=asc
)
getUri()
메서드를 사용하여 PSR-7 Request 개체의 URI object를 가져올 수 있습니다.
$uri = $request->getUri();
PSR-7 Request 객체의 URI는 HTTP 요청의 URL 부분을 검사하기 위해 다음과 같은 메소드를 제공하는 객체이다.
- getScheme()
- getAuthority()
- getUserInfo()
- getHost()
- getPort()
- getPath()
- getQuery() (returns the full query string, e.g.
a=1&b=2
) - getFragment()
getQueryParams()
를 사용하여 요청 개체의 연결 배열로 쿼리 매개 변수를 가져올 수 있습니다.