2016-07-05 136 views
0

我試圖從justinrainbow實現JSON-架構驗證的中間件修身3.苗條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. 有我需要怎麼就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 ,但我不明白,我應該返回容器,以及如何通過獲取/輸入後到容器

+0

你不能只在中間件中使用print_r()。嘗試這樣的代替'$ response-> write(print_r($ data),true))'' –

回答

0

你在第一點代碼似乎好了,你只嘗試從中間件中訪問路徑參數。此時路由尚未解析,因此不會從URL解析參數。

這是一個已知的用例,在Slim's documentation中有描述。將以下設置添加到您的應用程序的配置,讓您的代碼工作:

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

爲了瞭解中間件是如何工作以及如何操作響應對象,我建議你閱讀User Guide - 它不是那麼長,說明它真的好。