MVC API Request – Where to Place API Requests in MVC

apimvc

I'm building a web application using a MVC pattern. Following this kind of architecture we can see that all the methods used to interact with database are implemented in the model.

But what happen if I have to call a service exposed by others on web? For example, I would like to access the Facebook API in order to get all the follower of my page, so, where I put these methods?

Obviously the view is not a good idea because this module is dedicated to the presentation, the controller should not be used to retrieve data but the model is usually dedicated only to the interaction with database.

So, can you give me some hint about that? And please, can you tell me if I'm making some mistakes about the MVC architecture?

Best Answer

The model is not limited to interaction with the database, the model is responsible for getting and manipulating data.

So, to your view and controller, it should make no difference, if the data comes from a database or from a webservice or is even totally random, therefore you should do it in model.

MVC is a presentation pattern, that only separates the different representation layers.

It does not mean, that model has to be a uniform mess of spaghetti code. Your model itself can be layered as well, but the controller should not know, where the data comes from.

A public method in your model can be structured like this (Pseudo-code), which can be called by your controller:

public MyDataClass getData(int id) {
    WebServiceData wsData = WebService->getData(id);
    DatabaseData dbData = ORM->getData(id);
    return new MyDataClass(wsData, dbData);
}

WebService and ORM may need to be instances of interfaces that can be replaced by mocks via dependency injection, but your controllers and views do not have to change for testing purposes.

Related Topic