Lisa
Lisa

Reputation: 2139

Using Laravel with an existing API

Currently my Laravel application runs primarily off of a custom API that is consumed directly in the controllers using Guzzle. The only part of the site that is handled through Eloquent is User management/authentication. (The controllers extend a parent controller that has generic GET/PUT/POST calls in individual functions, and the child controllers call those functions and send them data)

I'm looking for information about how to abstract the API's GET/PUT/PUSH calls a bit more and get them out of the controllers so data access is more uniform across the board. Unfortunately I'm not seeing a whole lot of information on API's without actually creating them within your Laravel app.

It seems like I should be able to write something so the controllers interact with the API in a similar fashion to how they interact with the User data, but again, I'm not finding information about it (I'm probably googling it incorrectly).

Can someone point me in the right direction? I'm using Laravel 4.1.

Upvotes: 0

Views: 984

Answers (2)

joshuahornby10
joshuahornby10

Reputation: 4292

Check out my package

https://github.com/joshhornby/Http

Should help :)

Upvotes: 1

Kryten
Kryten

Reputation: 15780

It sounds like you're using Guzzle to connect to a third-party API and you want to get away from instantiating Guzzle & calling Guzzle method in your controllers.

One solution would be to write a library class that handles the API calls. For example

class MyAPILibrary
{
    public function readImportantData($parameters)
    {
        // use Guzzle to connect to the API, pass the parameters, and read
        // the important data
        return $importantData;
    }
}

Then, in your controller, whenever you need that data:

public function getIndex()
{
    // I need that important data!
    $d = MyAPILibrary::readImportantData($myParameters);

    // and use the data...
    return View::make("template")->with("important", $d);
}

Note that I've assumed you set up a service provider & facade for the library, so you can make method calls like MyAPILibrary::readImportantData($myParameters). For a good tutorial on that, see this page.

The nice thing about this setup is that you can now test the heck out of your API library without touching your controllers. Plus your controllers become much lighter - often one or two lines. For example, the example above can be rewritten:

public function getIndex()
{
    return View::make("template")
        ->with("important", MyAPILibrary::readImportantData($myParameters));
}

Voila! A one-line controller method!

Upvotes: 3

Related Questions