1
votes

Context: Laravel 5. Guzzle ~5.2. PHP 5.4. I'm building a class to interact with an external API. I'm providing this class with a Guzzle client using a Service Provider, to avoid instantiating the client within a method.

I want to cache the results. If the user is asking for something that is found in the cache, return it instead of performing a request to said API.

Problem: If I build up a Guzzle client and don't perform a request, the application crashes. Not even a stack trace from PHP. Actually, if I'm using Laravel's artisan serve, a Windows error message shows up saying, PHP CLI has stopped working.

For now, I'm passing the Guzzle client to the method on my class, every single time I call it.

Is there a way to just instantiate the Guzzle client without sending a request? What other route would you choose to achieve this? Is that intended behaviour?

2

2 Answers

1
votes

tl;dr RTM

Longer version (from the docs):

Creating Requests You can create a request without sending it. This is useful for building up requests over time or sending requests in concurrently.

$request = $client->createRequest('GET', 'http://httpbin.org', [
    'headers' => ['X-Foo' => 'Bar']
]);

// Modify the request as needed

$request->setHeader('Baz', 'bar');

After creating a request, you can send it with the client’s send() method.

$response = $client->send($request);
0
votes

from here: http://docs.guzzlephp.org/en/stable/quickstart.html#making-a-request

    use GuzzleHttp\Psr7\Request;

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'http://httpbin.org',
    // You can set any number of default request options.
    'timeout'  => 2.0,
]);

    $request = new Request('PUT', 'http://httpbin.org/put');
    $response = $client->send($request, ['timeout' => 2]);