简体   繁体   English

中间件Slim v3中的路由模式

[英]Route pattern in middleware Slim v3

How can I get route pattern inside middleware: 如何在中间件中获取路由模式:

routes.php: route.php:

$app->get('/myroute/{id}', function($req, $res, $args) {
//DO STUFF HERE
})->add(new MyMiddle());

middle.php: middle.php:

class MyMiddle {
    public function __invoke($req, $res, $next) {
         //DO STUFF
    }
}

In routes.php I can get {id} with $args['id'] , but how can I get it inside MyMiddle.php? 在routes.php中,我可以使用$args['id']获得{id} ,但是如何在MyMiddle.php中获得它?

Thank you, 谢谢,
Cristian Molina 克里斯蒂安·莫利纳(Cristian Molina)

  1. Enable the determineRouteBeforeAppMiddleware setting: 启用determineRouteBeforeAppMiddleware设置:

     $config = ['settings' => [ 'determineRouteBeforeAppMiddleware' => true, 'displayErrorDetails' => true, ]]; $app = new \\Slim\\App($config); 
  2. You can now access the Route object from the Request, using getAttribute() and, from the route, get at the arguments: 现在,您可以使用getAttribute()从请求中访问Route对象,并从路由获取参数:

     $app->add(function ($request, $response, $next) { $id = $request->getAttribute('route')->getArgument('id'); return $next($request, $response); }); 

I decided to included a Slim v2 example as that is what I was looking for when I came across this post. 我决定包含一个Slim v2示例,因为这是我在遇到这篇文章时所寻找的。 You can use $this->app->router()->getCurrentRoute()->getPattern() from the slim.before.dispatch callback hook to accomplish the same thing. 您可以使用slim.before.dispatch回调钩子中的$this->app->router()->getCurrentRoute()->getPattern()完成相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM