从控制器LARAVEL 4调用外部API函数

时间:2022-08-15 16:56:03

I build an API on laravel 4, and it returns json results. For the API, I created one folder. Now i created another external project for the web application and what I want is to access the API functions from the laravel app controller. To be more clear, how can i make external API request from laravel controller?

我在laravel 4上构建了一个API,它返回了json结果。对于API,我创建了一个文件夹。现在我为Web应用程序创建了另一个外部项目,我想要的是从laravel app控制器访问API函数。为了更清楚,我如何从laravel控制器发出外部API请求?

1 个解决方案

#1


37  

You can use Guzzle:

你可以使用Guzzle:

Install it:

安装它:

composer require guzzle/guzzle ~3.0

Create a client setting the base URL:

创建设置基本URL的客户端:

$client = new \Guzzle\Service\Client('http://api.github.com/users/');

Get your response:

得到你的回复:

$response = $client->get("users/$username")->send();

And display it:

并显示它:

dd($response);

But if you are trying to follow the MVC pattern, you should not do this directly in your controller, so create a service class, you call from your controller or your repositories, to do this work for you.

但是如果你试图遵循MVC模式,你不应该直接在你的控制器中这样做,所以创建一个服务类,你从你的控制器或你的存储库调用,为你做这项工作。

#1


37  

You can use Guzzle:

你可以使用Guzzle:

Install it:

安装它:

composer require guzzle/guzzle ~3.0

Create a client setting the base URL:

创建设置基本URL的客户端:

$client = new \Guzzle\Service\Client('http://api.github.com/users/');

Get your response:

得到你的回复:

$response = $client->get("users/$username")->send();

And display it:

并显示它:

dd($response);

But if you are trying to follow the MVC pattern, you should not do this directly in your controller, so create a service class, you call from your controller or your repositories, to do this work for you.

但是如果你试图遵循MVC模式,你不应该直接在你的控制器中这样做,所以创建一个服务类,你从你的控制器或你的存储库调用,为你做这项工作。