php Laravel 从 REST API 检索数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19124018/
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
Laravel retrieving data from REST API
提问by Tomkarho
Okay so I have a following situation:
好的,所以我有以下情况:
The system I am building is retrieving data from a REST api and saving that data into a database. What I am wondering is how could this be implemented and where would behaviour like this go in sense of Laravels structure (controller, model etc.)? Does Laravel have a built in mechanism to retrieve data from external sources?
我正在构建的系统正在从 REST api 检索数据并将该数据保存到数据库中。我想知道的是如何实现这一点,在 Laravel 结构(控制器、模型等)的意义上,这样的行为会发生在哪里?Laravel 是否具有从外部来源检索数据的内置机制?
采纳答案by devo
First you have to make routes in your app/routes.php
首先你必须在你的 app/routes.php
/*
API Routes
*/
Route::group(array('prefix' => 'api/v1', 'before' => 'auth.basic'), function()
{
Route::resource('pages', 'PagesController', array('only' => array('index', 'store', 'show', 'update', 'destroy')));
Route::resource('users', 'UsersController');
});
Note:If you are not required authentication for API call, you can remove 'before' => 'auth.basic'
注意:如果API调用不需要认证,可以去掉'before' => 'auth.basic'
Here you can access index, store, show, update and destroy
methods from your PagesController
.
在这里,您可以index, store, show, update and destroy
从您的PagesController
.
And the request urls will be,
请求网址将是,
GET http://localhost/project/api/v1/pages // this will call index function
POST http://localhost/project/api/v1/pages // this will call store function
GET http://localhost/project/api/v1/pages/1 // this will call show method with 1 as arg
PUT http://localhost/project/api/v1/pages/1 // this will call update with 1 as arg
DELETE http://localhost/project/api/v1/pages/1 // this will call destroy with 1 as arg
The command line CURL request will be like this (here the username and password are admin
) and assumes that you have .htaccess
file to remove index.php
from url,
命令行 CURL 请求将是这样的(这里的用户名和密码是admin
)并假设您有要从 url 中.htaccess
删除的文件index.php
,
curl --user admin:admin localhost/project/api/v1/pages
curl --user admin:admin -d 'title=sample&slug=abc' localhost/project/api/v1/pages
curl --user admin:admin localhost/project/api/v1/pages/2
curl -i -X PUT --user admin:admin -d 'title=Updated Title' localhost/project/api/v1/pages/2
curl -i -X DELETE --user admin:admin localhost/project/api/v1/pages/1
Next, you have two controllers named PagesController.php
and UsersController.php
in your app/controllers
folder.
接下来,您的文件夹中有两个名为PagesController.php
和 的控制器。UsersController.php
app/controllers
The PagesController.php,
PagesController.php,
<?php
class PagesController extends BaseController {
/**
* Display a listing of the resource.
*
* @return Response
* curl --user admin:admin localhost/project/api/v1/pages
*/
public function index() {
$pages = Page::all();;
return Response::json(array(
'status' => 'success',
'pages' => $pages->toArray()),
200
);
}
/**
* Store a newly created resource in storage.
*
* @return Response
* curl --user admin:admin -d 'title=sample&slug=abc' localhost/project/api/v1/pages
*/
public function store() {
// add some validation also
$input = Input::all();
$page = new Page;
if ( $input['title'] ) {
$page->title =$input['title'];
}
if ( $input['slug'] ) {
$page->slug =$input['slug'];
}
$page->save();
return Response::json(array(
'error' => false,
'pages' => $page->toArray()),
200
);
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
* curl --user admin:admin localhost/project/api/v1/pages/2
*/
public function show($id) {
$page = Page::where('id', $id)
->take(1)
->get();
return Response::json(array(
'status' => 'success',
'pages' => $page->toArray()),
200
);
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
* curl -i -X PUT --user admin:admin -d 'title=Updated Title' localhost/project/api/v1/pages/2
*/
public function update($id) {
$input = Input::all();
$page = Page::find($id);
if ( $input['title'] ) {
$page->title =$input['title'];
}
if ( $input['slug'] ) {
$page->slug =$input['slug'];
}
$page->save();
return Response::json(array(
'error' => false,
'message' => 'Page Updated'),
200
);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
* curl -i -X DELETE --user admin:admin localhost/project/api/v1/pages/1
*/
public function destroy($id) {
$page = Page::find($id);
$page->delete();
return Response::json(array(
'error' => false,
'message' => 'Page Deleted'),
200
);
}
}
Then you have model named Page
which will use table named pages
.
然后你有模型命名Page
,它将使用名为的表pages
。
<?php
class Page extends Eloquent {
}
You can use Laravel4 Generators to create these resources using php artisan generator
command. Read here.
你可以使用 Laravel4 Generatorsphp artisan generator
命令来创建这些资源。在这里阅读。
So using this route grouping you can use the same application to make API request and as a front-end.
因此,使用此路由分组,您可以使用相同的应用程序来发出 API 请求并作为前端。
回答by fideloper
Edit:Buzzhasn't been updated for over a year, it's recomended to now use Guzzle, see Mohammed Safeer'sanswer.
编辑:Buzz已经一年多没有更新了,建议现在使用Guzzle,请参阅Mohammed Safeer 的回答。
I have used Buzz packagein order to make API requests.
我使用Buzz 包来发出 API 请求。
You can add this package by adding it to the require
section in your composer.json
file.
您可以通过将其添加到文件中的require
部分来添加此包composer.json
。
{
require: {
"kriswallsmith/buzz": "dev-master"
}
}
Then run composer update
to get it installed.
然后运行composer update
以安装它。
Then in Laravel you can wrap it in a class (perhaps a repository-like class) that handles making API request and returning data for your app to use.
然后在 Laravel 中,您可以将它包装在一个类(可能是一个类似存储库的类)中,该类处理 API 请求并返回数据供您的应用程序使用。
<?php namespace My\App\Service;
class SomeApi {
public function __construct($buzz)
{
$this->client = $buzz;
}
public function getAllWidgets()
{
$data = $this->client->get('http://api.example.com/all.json');
// Do things with data, etc etc
}
}
Note: This is pseudocode. You'll need to create a class that works for your needs, and do any fancy dependency injection or code architecture that you want/need.
注意:这是伪代码。您需要创建一个满足您需求的类,并执行您想要/需要的任何花哨的依赖注入或代码架构。
As @Netbulae pointed out, a Repository might help you. The article he linkedis a great place to start. The only difference between the article and what your code will do is that instead of using an Eloquent model to get your data from your database, you're making an API request and transforming the result into a set of arrays/objects that your application can use (Essentially, just the data storage is different, which is one of the benefits of bothering with a repository class in the first place).
正如@Netbulae 指出的那样,存储库可能会对您有所帮助。他链接的文章是一个很好的起点。本文与您的代码将执行的操作之间的唯一区别是,您不是使用 Eloquent 模型从数据库中获取数据,而是发出 API 请求并将结果转换为应用程序可以使用的一组数组/对象使用(本质上,只是数据存储不同,这是首先使用存储库类的好处之一)。
回答by Mohammed Safeer
We can use package Guzzlein Laravel, it is a PHP HTTP client to send HTTP requests.
我们可以在 Laravel 中使用Guzzle包,它是一个发送 HTTP 请求的 PHP HTTP 客户端。
You can install Guzzle through composer
你可以通过 composer 安装 Guzzle
composer require guzzlehttp/guzzle:~6.0
Or you can specify Guzzle as a dependency in your project's existing composer.json
或者您可以在项目现有的 composer.json 中将 Guzzle 指定为依赖项
{
"require": {
"guzzlehttp/guzzle": "~6.0"
}
}
Example code in laravel 5 using Guzzle as shown below,
Laravel 5 中使用 Guzzle 的示例代码如下所示,
use GuzzleHttp\Client;
class yourController extends Controller {
public function saveApiData()
{
$client = new Client();
$res = $client->request('POST', 'https://url_to_the_api', [
'form_params' => [
'client_id' => 'test_id',
'secret' => 'test_secret',
]
]);
$result= $res->getBody();
dd($result);
}
回答by tsveti_iko
回答by Skid Kadda
Try looking into the external API's manuals. There you will find info on how to retrieve information.
尝试查看外部 API 的手册。在那里您将找到有关如何检索信息的信息。
Then the best plan is to build an Interface. Check this out: http://culttt.com/2013/07/08/creating-flexible-controllers-in-laravel-4-using-repositories/
那么最好的计划是构建一个接口。看看这个:http: //culttt.com/2013/07/08/creating-flexible-controllers-in-laravel-4-using-repositories/
It's up to you how you use php to solve this.
这取决于您如何使用 php 来解决这个问题。