2015-09-21 69 views
2

有没有办法在全球范围内增加form_params与狂饮6所有的请求?默认form_params为狂饮6

例如:

$client = new \GuzzleHttp\Client([ 
    'global_form_params' => [ // This isn't a real parameter 
     'XDEBUG_SESSION_START' => '11845', 
     'user_token' => '12345abc', 
    ] 
]); 

$client->post('/some/web/api', [ 
    'form_params' => [ 
     'some_parameter' => 'some value' 
    ] 
]); 

在我的理想世界里,post将有array_merge-ING global_form_paramsform_params结果:

[ 
    'XDEBUG_SESSION_START' => '11845', 
    'user_token' => '12345abc', 
    'some_parameter' => 'some value', 
] 

我可以看到也希望像这样的queryjson

回答

2

Creating a client你可以设置“任意数量的默认请求选项”,并在GuzzleHttp\Client Source Code

$client = new Client['form_params' => [form values],]); 

将适用于您的form_params每一个要求。

由于在Client::applyOptions内更改了Content-Type标头,这可能会导致GET请求出现问题。它最终取决于服务器配置。

如果你的意图是让客户端使双方GET和POST请求,那么你可能被form_params移动到中间件得到更好的服务。例如:

$stack->push(\GuzzleHttp\Middleware::mapRequest(function (RequestInterface $request) { 
    if ('POST' !== $request->getMethod()) { 
     // pass the request on through the middleware stack as-is 
     return $request; 
    } 

    // add the form-params to all post requests. 
    return new GuzzleHttp\Psr7\Request(
     $request->getMethod(), 
     $request->getUri(), 
     $request->getHeaders() + ['Content-Type' => 'application/x-www-form-urlencoded'], 
     GuzzleHttp\Psr7\stream_for($request->getBody() . '&' . http_build_query($default_params_array)), 
     $request->getProtocolVersion() 
    ); 
}); 
+0

我给了这个镜头,但我想合并“默认”form_params与每个请求中指定的任何内容。我认为我对“默认”这个词的使用还不清楚,我会更新我的问题。 –

+0

修改为反映所需的“合并” –