1

有什么方法可以使用中间件并根据某些参数发送多个请求?

更具体地说,我需要:

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);
        };
    }
}
4

1 回答 1

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()
        );
    }   
);
于 2015-10-31T03:59:36.770 回答