0

我正在尝试将justinrainbow的 json-schema 验证器实现为 Slim 3 中的中间件。

  1. 我不知道如何从中间件中的 GET/POST 请求中获取客户端输入。像这样尝试:

    $mw = function ($request, $response, $next) {
        $data = $request->getParsedBody();
        print_r($data); // prints nothing
        $id = $request->getAttribute('loan_id');
        print_r($id); // prints nothing
    
        // here I need to validate the user input from GET/POST requests with json-schema library and send the result to controller
        $response = $next($request, $response);
        return $response;
    };
    
    $app->get('/loan/{loan_id}', function (Request $request, Response $response) use ($app, $model) {
        $loanId = $request->getAttribute('loan_id'); // here it works
        $data = $model->getLoan($loanId);
        $newResponse = $response->withJson($data, 201);
    
        return $newResponse;
    })->add($mw);
    
  2. 我需要它有两种可能的方式。我做错了什么?

    1. 在中间件中验证它并向控制器发送一些数组/json响应,然后我会得到我所理解的$data = $request->getParsedBody();

    2. 在中间件中验证它,但最终检查将在控制器中进行,如下所示:

      $app->get('/loan/{loan_id}', function (Request $request, Response $response) use ($app, $model) {
          if($validator->isValid()){
              // 
          }
          $loanId = $request->getAttribute('loan_id'); // here it works
          $data = $model->getLoan($loanId);
          $newResponse = $response->withJson($data, 201);
      
          return $newResponse;
      })->add($mw);
      

对我来说最好的选择它做类似这里的事情, 但我不明白我应该在容器中返回什么,以及如何将 get/post 输入传递给容器

4

1 回答 1

0

您在第一点的代码似乎没问题,您只尝试从中间件中访问路由参数。此时路由尚未解析,因此不会从 URL 解析参数。

这是一个已知的用例,在Slim 的文档中进行了描述。将以下设置添加到您的应用配置中以使您的代码正常工作:

$app = new App([
    'settings' => [
        // Only set this if you need access to route within middleware
        'determineRouteBeforeAppMiddleware' => true
    ]
]);

为了理解中间件是如何工作的以及如何操作响应对象,我建议你阅读用户指南——它并不长,而且解释得很好。

于 2016-07-09T22:48:22.380 回答