苗条 3 中间件验证


Slim 3 middleware validation

我正在尝试将 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);
      

对我来说最好的选择,它像这里一样做 但我不明白我应该在容器中返回什么,以及如何将获取/发布输入传递给容器

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

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

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

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