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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22694289/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:11:13  来源:igfitidea点击:

Call external API function from controller, LARAVEL 4

phplaravellaravel-4

提问by Deep Dizzy

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 应用程序控制器访问 API 函数。更清楚地说,我如何从 laravel 控制器发出外部 API 请求?

回答by Antonio Carlos Ribeiro

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 模式,你不应该直接在你的控制器中这样做,所以创建一个服务类,你从你的控制器或你的存储库中调用,来为你完成这项工作。