【问题标题】:How can I use a class from vendor folder in laravel project如何在 laravel 项目中使用供应商文件夹中的类
【发布时间】:2018-06-09 07:50:42
【问题描述】:

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

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

我在这里缺少什么,请帮助我。谢谢。

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

【问题讨论】:

  • 你不需要将它添加到你的 composer.json 中。你跑了吗composer dumpautoload
  • 你在config/app.php中注册了包吗
  • @RahulReghunath 不,我没有。
  • @aynber,是的,我运行了这个命令。

标签: php laravel guzzle


【解决方案1】:

简短版:您正在尝试实例化一个不存在的类。实例化正确的类,你就万事大吉了。

长版:您不需要对您的 composer.json 做任何花哨的事情来让 Guzzle 工作。 Guzzle 遵循 PSR 自动加载标准,这意味着只要 Guzzle 通过 composer 引入,您就可以实例化 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;

你应该准备好了。

【讨论】:

  • 谢谢 :) 它有效,感谢您的解释!
猜你喜欢
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
相关资源
最近更新 更多