2015-10-21 46 views
1

有什麼辦法可以使用中間件並根據某些參數使用guzzle發送多個請求?通過Guzzle中的中間件發送多個請求

更具體,我需要:

class MyMiddleware 
{ 
    /** 
    * @param callable $handler 
    * @return \Closure 
    */ 
    public function __invoke(callable $handler) 
    { 
     return function (RequestInterface $request, array $options) use ($handler) { 
      if(!isset($options['token']){ 
       //request the token from a url 
      } 
      //after the token is aquired proceed with the original request 
      return $handler($request, $options); 
     }; 
    } 
} 

回答

0

這是類似於你所查詢的是什麼?我做了類似的事情。

$handler = GuzzleHttp\HandlerStack::create(); 

$client = new GuzzleHttp\Client([ 
    'handler' = $handler, 
    // other options 
]) 

$handler->push(GuzzleHttp\Middleware::mapRequest(
    function (Psr\Http\Message\RequestInterface $request) use ($client) { 
     if ('POST' !== $request->getMethod()) { 
      return $request; 
     } 
     if($RequestIsOkAsIs) { 
      return $request; 
     } 

     $response = $client->get($someUrl, $requestOptions); 

     // Play with the response to modify the body 
     $newBody = 'results of stuff'; 

     return new GuzzleHttp\Psr7\Request(
      $request->getMethod(), 
      $request->getUri(), 
      $request->getHeaders(), 
      $newBody, 
      $request->getProtocolVersion() 
     ); 
    } 
);