35

わかりましたので、次の状況があります。

私が構築しているシステムは、REST API からデータを取得し、そのデータをデータベースに保存しています。私が疑問に思っているのは、これをどのように実装できるか、そしてこのような動作は Laravels 構造 (コントローラー、モデルなど) の意味でどこに行くのでしょうか? Laravel には、外部ソースからデータを取得するメカニズムが組み込まれていますか?

4

5 に答える 5

44

編集: Buzzは 1 年以上更新されていません。現在は Guzzle を使用することをお勧めします。Mohammed Safeer の回答を参照してください。


API リクエストを行うためにBuzz パッケージを使用しました。

requireこのパッケージは、ファイルのセクションに追加することで追加できcomposer.jsonます。

{
    require: {
        "kriswallsmith/buzz": "dev-master"
    }
}

次に、実行composer updateしてインストールします。

次に、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
    }

}

注: これは疑似コードです。必要に応じて機能するクラスを作成し、必要な/必要なファンシーな依存性注入またはコード アーキテクチャを実行する必要があります。

@Netbulae が指摘したように、リポジトリが役立つ場合があります。彼がリンクした記事は、始めるのに最適な場所です。この記事とあなたのコードが行うこととの唯一の違いは、Eloquent モデルを使用してデータベースからデータを取得する代わりに、API リクエストを作成し、結果をアプリケーションで使用できる一連の配列/オブジェクトに変換していることです。を使用します (基本的に、データ ストレージが異なるだけです。これは、最初にリポジトリ クラスを使用する利点の 1 つです)。

于 2013-10-01T20:59:52.127 に答える
31

パッケージGuzzleを Laravel で使用できます。これは、HTTP リクエストを送信するための PHP HTTP クライアントです。

composer から Guzzle をインストールできます。

composer require guzzlehttp/guzzle:~6.0

または、プロジェクトの既存の composer.json で Guzzle を依存関係として指定できます。

{
   "require": {
      "guzzlehttp/guzzle": "~6.0"
   }
}

以下に示すように、Guzzleを使用したlaravel 5のコード例、

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);

}
于 2015-09-14T16:35:50.493 に答える
9

使用するものを選択できます。

  1. ガズル
  2. カール
  3. file_get_contents :

    $json = json_decode(file_get_contents('http://host.com/api/v1/users/1'), true);
    

リファラー

于 2016-08-23T13:54:09.823 に答える
9

まず、ルートを作成する必要があります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');
});

注: API 呼び出しに認証が必要ない場合は、削除できます。'before' => 'auth.basic'

index, store, show, update and destroyここで、 からメソッドにアクセスできますPagesController

リクエスト URL は次のようになります。

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

コマンド ラインの CURL リクエストは次のようになり (ここではユーザー名とパスワードは)、 URLから削除するファイルadminがあると仮定します。.htaccessindex.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

次に、フォルダに and という名前の 2 つのコントローラがありPagesController.phpます。UsersController.phpapp/controllers

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
        );
    }

}

Page次に、という名前のテーブルを使用するという名前のモデルがありますpages

<?php

class Page extends Eloquent {
}

Laravel4 ジェネレーターを使用して、php artisan generatorコマンドを使用してこれらのリソースを作成できます。ここを読んでください。

したがって、このルート グループ化を使用すると、同じアプリケーションを使用して API リクエストを作成し、フロントエンドとして使用できます。

于 2013-10-02T08:26:16.307 に答える
2

外部 API のマニュアルを調べてみてください。そこには、情報を取得する方法に関する情報があります。

次に、最善の計画は、インターフェイスを構築することです。これをチェックしてください: http://culttt.com/2013/07/08/creating-flexible-controllers-in-laravel-4-using-repositories/

これを解決するためにphpをどのように使用するかはあなた次第です。

于 2013-10-01T19:17:45.930 に答える