Call external API function from controller, LARAVEL 4(从控制器调用外部 API 函数,LARAVEL 4)
问题描述
我在 laravel 4 上构建了一个 API,它返回 json 结果.对于 API,我创建了一个文件夹.现在我为 Web 应用程序创建了另一个外部项目,我想要的是从 laravel 应用程序控制器访问 API 函数.更清楚地说,我如何从 laravel 控制器发出外部 API 请求?
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?
推荐答案
你可以使用 Guzzle:
安装它:
composer require guzzle/guzzle ~3.0
创建一个设置基本 URL 的客户端:
Create a client setting the base URL:
$client = new GuzzleServiceClient('http://api.github.com/users/');
得到你的回应:
$response = $client->get("users/$username")->send();
并显示它:
dd($response);
但是,如果您尝试遵循 MVC 模式,则不应直接在控制器中执行此操作,因此请创建一个服务类,从您的控制器或存储库中调用,为您完成此工作.
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.
这篇关于从控制器调用外部 API 函数,LARAVEL 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从控制器调用外部 API 函数,LARAVEL 4
基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
