如何在laravel项目中使用vendor文件夹中的类

问题描述 投票:5回答:1

我试图从供应商文件夹中包含guzzle http客户端并使用composer。这是我到目前为止所尝试的。

guzzle http客户端文件vendor/guzzle/guzzle/src/Guzzle/Http/Client.php的位置

在我包括的composer.json文件中

"autoload": {
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "files":["vendor/guzzle/guzzle/src/Guzzle/Http/Client.php"],
    "psr-4": {
        "App\\": "app/"
    }
},

我跑了命令composer dumpautoload

在我的控制器中,我试图像这样调用api终点

use GuzzleHttp\Client;
$client = new Client(); // this line gives error 
$res = $client->get('https://api.fixer.io/latest?symbols=CZK,EURO');

错误是Class 'GuzzleHttp\Client' not found

我在这里失踪了,请帮助我。谢谢。

为了更好的文件结构,这里是文件位置enter image description here的屏幕截图

php laravel guzzle
1个回答
6
投票

简短版本:您正在尝试实例化一个不存在的类。实例化正确的班级,你就可以完成任务。

长版:你不应该对你的composer.json做任何想要让Guzzle工作的东西。 Guzzle坚持自动加载的PSR标准,这意味着只要Guzzle通过作曲家进入,你可以实例化Guzzle类而不必担心自动加载。

根据您提到的文件路径,它听起来是like you're using Guzzle 3。特别关注the class you're trying to include

namespace Guzzle\Http;
/*...*/
class Client extends AbstractHasDispatcher implements ClientInterface
{
        /*...*/
}

Guzzle 3中的guzzle客户端类不是GuzzleHttp\Client。它的名字是Guzzle\Http\Client。所以试试吧

$client = new \Guzzle\Http\Client;

要么

use Guzzle\Http\Client;
$client = new Client;

你应该全力以赴。

© www.soinside.com 2019 - 2024. All rights reserved.