
마지막 슬래쉬(/) 라우트 패턴 (Trailing / in route patterns)
Slim은 마지막에 슬래시가 있는 URL 패턴을 없는 URL 패턴과 다르게 처리합니다. 즉, /user
와 /user/
는 다르므로 서로 다른 콜백을 부착할 수 있습니다.
For GET requests a permanent redirect is fine, but for other request methods like POST or PUT the browser will send the second request with the GET method. To avoid this you simply need to remove the trailing slash and pass the manipulated url to the next middleware.
GET 요청의 경우 영구적인 리디렉션은 괜찮지만 POST 또는 PUT와 같은 다른 요청 방법의 경우 브라우저는 GET 메서드와 함께 두 번째 요청을 보낼 것이다. 이 문제를 방지하려면 후행 슬래시를 제거하고 조작된 url을 다음 미들웨어에 전달하기만 하면 됩니다.
/
로 끝나는 모든 URL을 비트레이링 /
에 해당하는 URL로 리디렉션/다시 쓰려면 다음 미들웨어를 추가할 수 있습니다.
<?php
use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Factory\AppFactory;
use Slim\Psr7\Response;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$app->add(function (Request $request, RequestHandler $handler) {
$uri = $request->getUri();
$path = $uri->getPath();
if ($path != '/' && substr($path, -1) == '/') {
// recursively remove slashes when its more than 1 slash
$path = rtrim($path, '/');
// permanently redirect paths with a trailing slash
// to their non-trailing counterpart
$uri = $uri->withPath($path);
if ($request->getMethod() == 'GET') {
$response = new Response();
return $response
->withHeader('Location', (string) $uri)
->withStatus(301);
} else {
$request = $request->withUri($uri);
}
}
return $handler->handle($request);
});
또는 모든 URL에 후행 슬래시를 강제 추가할 수 있는 middlewares/middlewares 미들웨어를 고려해 보십시오.
use Middlewares\TrailingSlash;
$app->add(new TrailingSlash(true)); // true adds the trailing slash (false removes it)
현재 경로 검색 (Retrieving Current Route)
프로그램 내에서 현재 경로에 액세스해야 하는 경우 수신되는 ServerRequestInterface
를 사용하여 RouteContext
개체를 인스턴스화해야 합니다.
여기서 ‘$routeContext->getRoute()’를 통해 경로를 가져오고 ‘getName()’을 사용하여 경로 이름에 액세스하거나 ‘getMethods()’를 통해 이 경로가 지원하는 메소드를 가져올 수 있습니다.
참고: 경로 핸들러에 도달하기 전에 미들웨어 주기 중에 ‘RouteContext’ 개체에 액세스해야 하는 경우 오류 처리 미들웨어 전에 ‘RoutingMiddleware’를 가장 바깥쪽 미들웨어로 추가해야 합니다 (아래 예 참조).
예:
<?php
use Slim\Exception\HttpNotFoundException;
use Slim\Factory\AppFactory;
use Slim\Routing\RouteContext;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
// Via this middleware you could access the route and routing results from the resolved route
$app->add(function (Request $request, RequestHandler $handler) {
$routeContext = RouteContext::fromRequest($request);
$route = $routeContext->getRoute();
// return NotFound for non existent route
if (empty($route)) {
throw new HttpNotFoundException($request);
}
$name = $route->getName();
$groups = $route->getGroups();
$methods = $route->getMethods();
$arguments = $route->getArguments();
// ... do something with the data ...
return $handler->handle($request);
});
// The RoutingMiddleware should be added after our CORS middleware so routing is performed first
$app->addRoutingMiddleware();
// The ErrorMiddleware should always be the outermost middleware
$app->addErrorMiddleware(true, true, true);
// ...
$app->run();