Building query string programmatically in Guzzle?

后端 未结 3 1644
轻奢々
轻奢々 2021-01-17 14:56

In my PHP Guzzle client code, I have something like

$c = new Client(\'http://test.com/api/1.0/function\');

$request = $c->get(\'?f=4&l=2&p=3&         


        
相关标签:
3条回答
  • 2021-01-17 15:22

    You can:

    $c = new Client('http://test.com/api/1.0/function');
    
    $request = $c->get();
    
    $q = $request->getQuery();
    
    $q->set('f', 4);
    $q->set('l', 2);
    $q->set('p', 3);
    $q->set('u', 5);
    
    0 讨论(0)
  • 2021-01-17 15:24

    Have a look at Guzzle documentaton https://docs.guzzlephp.org/en/stable/request-options.html As you can see it has RequestOptions. RequestOptions are constants. They are defined at GuzzleHttp\RequestOptions. You can look at class source code and see all of them right there. Thus, to keep good and professional programming style you can write following source code below, for example

    use GuzzleHttp\Client;
    use GuzzleHttp\RequestOptions;
    
    class DataClass extends BaseClass
    {
        const DEFAULT_ACCEPT_HEADER = 'application/json';
        const DEFAULT_CACHE_HEADER = 'no-cache';
        const HOST = 'http://test.com/';
        const ENDPOINT = 'api/1.0/function';
        const TIMEOUT = 2.0;
    
        private function getData()
        {
    
            $client = new Client([
                    'base_uri' => self::HTTP_HOST,
                    'timeout' => self::TIMEOUT
                ]
            );
    
            $response = $client->request('GET', self::ENDPOINT,
                [
                    RequestOptions::HEADERS => [
                        'Accept' => self::DEFAULT_ACCEPT_HEADER,
                        'Cache-Control' => self::DEFAULT_CACHE_HEADER,
                    ],
                    RequestOptions::QUERY => [
                            'f' => 4,
                            'l' => 2,
                            'p' => 3,
                            'u' => 5
                    ]
                ]
            );
    
            return json_decode($response->getBody(), JSON_OBJECT_AS_ARRAY);
        }
    
    0 讨论(0)
  • 2021-01-17 15:27

    Guzzle 6 - you could use query option param

    // Send a GET request to /get?foo=bar
    $client->request('GET', '/get', ['query' => ['foo' => 'bar']]);
    

    http://docs.guzzlephp.org/en/stable/request-options.html#query

    0 讨论(0)
提交回复
热议问题