2015-09-21 70 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

修改爲反映所需的「合併」 –