访问Slim v3中间件中的参数

2022-06-13 00:00:00 php slim

根据http://www.slimframework.com/docs/concepts/middleware.html,添加路由中间件如下。

<?php
$app = new SlimApp();

$mw = function ($request, $response, $next) {
    // How is $arg accessed?
    $response->getBody()->write('BEFORE');
    $response = $next($request, $response);
    $response->getBody()->write('AFTER');

    return $response;
};

$app->get('/ticket/{id}', function ($request, $response, $args) {
    $response->getBody()->write(' Hello ');
    // $arg will be ['id'=>123]
    return $response;
})->add($mw);

$app->run();

$arg将是参数数组。如何在中间件中访问它?

http://help.slimframework.com/discussions/questions/31-how-pass-route-pram-to-middleware显示了一种执行此操作的方法,但似乎是Slim的早期版本,错误Fatal error: Call to undefined method Slim\Route::getParams()


解决方案

路由参数可以根据请求通过routeInfo属性访问,这样

$app->get('/hello/{name}', HelloWorld::class . ':execute')
    ->add(function ($request, $response, $next) {
        var_dump($request->getAttribute('routeInfo')[2]['name']);exit();
        return $next($request, $response);
    });

this Github issue

中说明了这一点

相关文章