通过Guzzle中的中间件发送多个请求


Send multiple requests through a middleware in 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);
        };
    }
}

这与您所询问的内容相似吗?我做过类似的事。

$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()
        );
    }   
);