現在のルートの取得

アプリケーション内で現在のルートにアクセスする必要がある場合は、着信 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();