根据http://www.slimframework.com/docs/concepts/middleware.html,添加路由中间件如下:
<?php
$app = new 'Slim'App();
$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);
});
在这个Github问题