【问题标题】:Getting route path arguments in middleware在中间件中获取路由路径参数
【发布时间】:2018-08-08 07:36:54
【问题描述】:

在 Slim 3 中,我有一组具有相同操作的组,这取决于 $args

$this->group('{id}/', function () {
    $this->get('first/', function (Request $req, Response $res, $args) {
        $myData = operations($args['id']);
        ...
    });

    $this->post('second/', function (Request $req, Response $res, $args) {
        $myData = operations($args['id']);
        ...
    });
});

我可以将那些常见的操作转移到更高的级别。 我读到它可能是中间件,但在中间件中我不能(或不知道如何)访问$args

->add(function (ServerRequestInterface $request, ResponseInterface $response, callable $next) {
    //how to get arguments?
    $request = $request->withAttribute('myData', operations($id); 
    $response = $next($request, $response);

    return $response;
});

【问题讨论】:

    标签: php slim slim-3


    【解决方案1】:

    您可以通过路由信息属性的第三项访问路由参数:

    $routeParams = $request->getAttribute('routeInfo')[2];
    

    【讨论】:

      【解决方案2】:

      另一种方式:

      $route = $req->getAttribute('route');
      if (! is_null($route)) {
          print_r($route->getArguments()); // ['id' => 123]
          print_r($route->getArgument('id')); // 123
      }
      

      【讨论】:

        猜你喜欢
        • 2019-01-24
        • 2015-10-27
        • 1970-01-01
        • 2017-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-08
        • 2018-06-30
        相关资源
        最近更新 更多