【问题标题】:Slim 3 middleware validationSlim 3 中间件验证
【发布时间】:2016-11-07 00:15:32
【问题描述】:

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

对我来说最好的选择是here 但我不明白我应该在容器中返回什么,以及如何将 get/post 输入传递给容器

【问题讨论】:

  • 您不能只在中间件中使用print_r()。试试这样的东西$response->write(print_r($data), true))

标签: php slim middleware jsonschema slim-3


【解决方案1】:

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

这是一个已知的用例,在Slim's documentation 中有描述。将以下设置添加到您的应用配置中以使您的代码正常工作:

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

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

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 2017-11-15
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    相关资源
    最近更新 更多