Can't get Guzzle working in my Laravel app on

2019-07-25 12:47发布

问题:

I have a working PHP app running in Bluemix that I want to extend to call a RESTful service (Insights for Twitter). Since PHP has no built-in way to call the service, I looked around and decided to use Guzzle.

I downloaded Guzzle 6.0.2 from its Git and imported the zip into my httdocs/vendor path and renamed the imported path GuzzleHttp I changed my buildpack to get PHP 5.5 and updated composer.json to the Autoload.psr4 property with:

"GuzzleHttp\\": "htdocs/vendor/"

I redeployed my app and it still worked.

Then I added the following code to my MainController.php: after some other uses:

use GuzzleHttp\Client;

and then later:

$client = new GuzzleHttp\Client([
// Base URI is used with relative requests
'base_uri' => 'https:myserviceURI.mybluemix.net',
// You can set any number of default request options.
'timeout'  => 2.0,
]);
// Use guzzle to send a GET request to Watson Twitter Insights
 $guzzleresponse = $client->request('GET', '/api/v1/messages/search');

Now, when I redeploy the app I get:

FatalErrorException in HomeController.php line 100:
Class 'App\Http\Controllers\GuzzleHttp\Client' not found

I don't know why it's looking in app\Http\Controllers\ but I tried copying the Guzzle src folder - which includes Client.php - there, renamed it GuzzleHttp and it still fails the same way.

I'm neither a PHP nor a Laravel expert. I inherited the code from an intern team so I don't quite know how all the pieces fit together.

I have some questions:

Did I really need to install Guzzle in my workspace or would it be picked up automatically from the buildpack?

Did I import the Guzzle code in the right way?

Why is it looking for the Guzzle Client in my Controllers path?

Is there a good PHP sample program that drives Insights for Twitter? I found one in Javascript but I need to run this server-side?

And of course, most importantly, what do I need to do to get this working?

Answers to any or all of these questions wold be greatly appreciated

回答1:

Since you added

use GuzzleHttp\Client;

You have to use Guzzle Client like this:

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

It tries to look for Guzzle Client in the Controllers path probably because your controller namespace is App\Http\Controllers and you are trying to use Guzzle client like new GuzzleHttp\Client



回答2:

   $client = new Client(array_merge([
        'base_uri' => 'URL',
        'timeout' => 30.0
    ]), $options);

/if you need options/

    $options = array_merge_recursive([
        RequestOptions::AUTH => [
            'Conversation_USERNAME',
            'CONVERSATION_PASSWORD',
        ],
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/json'
        ]
    ], $options);