简体   繁体   中英

Laravel (4.2): Where to put 3rd party API connection?

I am very new to Laravel and am wondering where would be the ideal place to put a connection to a 3rd party API. Here is the general flow of the request that needs to happen in my system

1) User enters input into form (using Angular to send data to backend

2) Routes file routes request to a controller i created in Laravel (I'm actually using a resource that i created using the laravel command line for this)

3) somewhere, i need to take some of the data from this request and send it via CURL to a 3rd party and get the response back

4) Somewhere else, I need to parse that response and run some business logic on it where i will take some of the results of that and send them back to the client. Other of the data will be saved into a data store (MySQL)

Now i presume that the data access layer will be the laravel model that i will eventually create, but i'm confused on where the ideal location is for the API connection stuff and also for the business logic stuff.

My first thought was this should be done via middleware, but upon reading the documentation further it now seems like this is just a filter layer. I could of course put this into the model and that would seem to satisfy the 'Fat Model Skinny Controller' paradigm, but i don't like that for some reason. I would like my data access layer to be independent of the business logic and i don't want to put all this crap into the controller either because this is clearly wrong.

So where should it go?

This is my suggestion:

Create a plain PHP class called ExternalAPI and save it in a folder called API inside the app folder. Then create a method to make the call to the API and to parse the results. You can even put this class inside a Facade to make it easier to use.

Then create another class to be responsible to receive the parsed data and to perform the business logic. Let's call it APIProcessor and let's save it in the app/API folder.

And finally, in the controller, you will call the method from the ExternalAPI class, pass the results to the APIProcessor class and then get the results from it and return back to the user.

Obviously that these names are bad and you should choose better names to these classes accordinily to your business domain and even choose another directories to save them if you want.

Another good thing to do here is to create an Interface to the class that will be responsible to communicate with the API, so you can easily substitute this class by another if necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM