简体   繁体   中英

Calling a REST API from an MVC Web Application

I have an MVC PHP web application that needs to call a REST API. I'm unclear on whether I should be calling the API from my controller or from the model? Looking at various resources I'm getting mixed information. I assume it should be from the Model since all I'm doing is dealing with data and passing that up to the controller correct?

Some more details to clarify. I do have full control over the REST API which I'm in the process of building and is in PHP as well. The API however will also be leveraged by an iOS and Android companion app built by my team and a few other apps running on proprietary devices.

The original plan was that the web app was not going to leverage the API and just go straight to the DB to cut out any overhead, but several debates later and I'm leaning toward using the API.

I'd call from the model if the REST resource is a representation of the model, or if you're going to need this functionality across multiple controllers.

Call from the controller if it is not 100% specific to the model representation, or if it is only important to the controller/view you're working with.

You should call the web API from the Controller . The Model is how the data is passed from the Controller to the View . The Model should only have data and no business logic.

When you get the response from the web API, the data should be put into the Model and passed to the View .

The Model , the View and the Controller make up the MVC pattern. The Controller is responsible for putting the data in to the Model, which it passes to the View. The View takes the Model and displays the data, as it has been told to. There is no Business Logic in either the Model or the View.

Ideally, you would put your API code into a class library, that the controller uses. This allows you to separate the business logic out of the website and into a separate component.

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