laravel 如何在laravel项目中使用供应商文件夹中的类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48012987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use a class from vendor folder in laravel project
提问by Shakil Ahmed
I am trying to include guzzle http client from a vendor folder and using composer. Here is what I have tried so far.
我正在尝试从供应商文件夹中包含 guzzle http 客户端并使用 Composer。这是我迄今为止尝试过的。
Location of guzzle http client file vendor/guzzle/guzzle/src/Guzzle/Http/Client.php
guzzle http客户端文件的位置 vendor/guzzle/guzzle/src/Guzzle/Http/Client.php
In composer.json file I included
在我包含的 composer.json 文件中
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"files":["vendor/guzzle/guzzle/src/Guzzle/Http/Client.php"],
"psr-4": {
"App\": "app/"
}
},
The I ran the command composer dumpautoload
.
I 运行命令composer dumpautoload
。
In my controller I am trying to call an api end point like this
在我的控制器中,我试图调用这样的 api 端点
use GuzzleHttp\Client;
$client = new Client(); // this line gives error
$res = $client->get('https://api.fixer.io/latest?symbols=CZK,EURO');
The error is Class 'GuzzleHttp\Client' not found
错误是 Class 'GuzzleHttp\Client' not found
What I am missing here, please help me. Thanks.
我在这里缺少什么,请帮助我。谢谢。
For a better file structure here is a screenshot of of the file location
回答by Alan Storm
Short Version: You're trying to instantiate a class that doesn't exist. Instantiate the right class and you'll be all set.
简短版本:您正在尝试实例化一个不存在的类。实例化正确的类,你就可以了。
Long Version: You shouldn't need to do anything fancy with your composer.json to get Guzzle working. Guzzle adheres to a the PSR standard for autoloading, which means so long as Guzzle's pulled in via composer, you can instantiate Guzzle classes without worrying about autoloading.
长版:你不需要对你的 composer.json 做任何花哨的事情来让 Guzzle 工作。Guzzle 遵守自动加载的 PSR 标准,这意味着只要 Guzzle 通过 Composer 引入,您就可以实例化 Guzzle 类而无需担心自动加载。
Based on the file path you mentioned, it sounds like you're using Guzzle 3. Looking specifically at the class you're trying to include
根据您提到的文件路径,听起来您正在使用 Guzzle 3。专门查看您要包含的课程
namespace Guzzle\Http;
/*...*/
class Client extends AbstractHasDispatcher implements ClientInterface
{
/*...*/
}
The guzzle client class in Guzzle 3 is not GuzzleHttp\Client
. Its name is Guzzle\Http\Client
. So try either
Guzzle 3 中的 Guzzle 客户端类不是GuzzleHttp\Client
. 它的名字是Guzzle\Http\Client
。所以尝试
$client = new \Guzzle\Http\Client;
or
或者
use Guzzle\Http\Client;
$client = new Client;
and you should be all set.
你应该准备好了。