How can I use a class from vendor folder in laravel project

戏子无情 提交于 2021-01-27 05:53:38

问题


I am trying to include guzzle http client from a vendor folder and using composer. Here is what I have tried so far.

Location of guzzle http client file vendor/guzzle/guzzle/src/Guzzle/Http/Client.php

In composer.json file I included

"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.

In my controller I am trying to call an api end point like this

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

What I am missing here, please help me. Thanks.

For a better file structure here is a screenshot of of the file location


回答1:


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.

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

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

$client = new \Guzzle\Http\Client;

or

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

and you should be all set.



来源:https://stackoverflow.com/questions/48012987/how-can-i-use-a-class-from-vendor-folder-in-laravel-project

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!