LoginSignup
1
2

More than 5 years have passed since last update.

Slim3のミドルウェアで、ルートパラメターにアクセスする方法

Last updated at Posted at 2017-10-26

Slim3に「Retrieving Current Route」というページがあるのに気がついたので、簡単に紹介します。

ミドルウェア内で、ルートパターンにマッチした結果にアクセスする方法です。

普通は、ルートパラメター(ルート内の{name}の部分)は、$argsに入ってきます。

$app->get('user/{name}', function($request, $response, $args) {
    $name = $args['name']; // 1. ルートパラメター:name
    // $nameを使って、適当に処理
    $response->getBody()->write("<h1>Hello {$name}</h1>");
    return $response;
});

では、ミドルウェアの場合は、どうやってアクセスするでしょう?
ミドルウェアだと$argsはありません。代わりに$nextがありますが。

その場合、$requestからrouteを取り出して使えるそうです。

use Slim\App;
use Slim\Exception\NotFoundException;
use Slim\Http\Request;
use Slim\Http\Response;

// 1. まず、設定内のフラグを追加!
$app = new App([
    'settings' => [
        // Only set this if you need access to route within middleware
        'determineRouteBeforeAppMiddleware' => true
    ]
]);

// ルートとミドルウェアの設定
$app->get('user/{name}', function($request, $response, $args) {

    $name = $args['name']; // 4. ルートパラメター:name
    // $nameを使って、適当に処理
    $response->getBody()->write("<h1>Hello {$name}</h1>");
    return $response;

})->add(function (Request $request, Response $response, callable $next) {

    // $routeを取得しておく
    $route = $request->getAttribute('route'); // 2. route取り出す
    $arguments = $route->getArguments();

    $arguments['name'] .= ' :touched!'; // 3. 名前に細工しとく
    $route->setArguments($arguments);

    return $next($request, $response);
});

大事なことは、最初にsettingsdetermineRouteBeforeAppMiddlewareフラグをtrueにしておくこと。これを唱えていないと、ミドルウェアを実行した後にルートのマッチングが行われるとのこと。

ルートパラメーターを変更したい場合は、routesetArgument(s)を使えます。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2