Calling a REST API from an MVC Web Application - php

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.

Related

REST api - Updating table with POST from view

I'm new to RESTful web services and still figuring out the design/architecture aspect coupled with MVC pattern. I am using Codeigniter framework to implement MVC.
I had a pretty simple question. I am using using form data to update a table in my database. I have written an api that will do this:
http://www.example.com/api/resource/tablename/?param1=info1...
Typical api. What I wanted to know was, in the MVC pattern should I be using cURL in my VIEW to POST data and update my table with the form data or should I still be send the POST data to my controller and make the api call from the controller to update the table.
To me it seems arbitrary at this point as both will accomplish the same thing but what is the standard practice? Is it okay to directly communicate with you api from the VIEW to update your db table??
Is it okay to directly communicate with you api from the VIEW to
update your db table??
Yes, it is...in fact that is pretty much what you should do in this case! Send your data directly to the API. Your API should do all data validation and return an error message (in a standardized format like JSON, XML etc) if any data validation fails OR perform whatever action it needs to do with the POSTed data. A great benefit in doing so would be that your API can be used by any caller and would be a complete ecosystem by itself.
Without knowing more about your intended applications I can say this:
Typically you want to try and keep any processing logic (PHP) out of your views if possible. The whole point of the controller is to handle transaction operations from your model and then pass it to your view. So if you are using an API to gather some data from a service that is intended to be used/manipulated in your view then the logical location for that would be in the controller.
The MVC pattern isn't a hard and fast law of X goes in Y and Y goes in Z. It is a pattern that makes it easy to extend and abstract your data gathering, processing logic, and visual layouts.
Technically depending on the application and how you planned to use it you could create a model for the API so that it could be used in multiple controllers without the need to re-write it.

Is it possible to separate Controller and View in RESTful Symfony app?

I am thinking about using Symfony to create a RESTful api. I want my app to only accept json and/or xml and just output either. I want my frontend to be completely separate in a separate directory.
Disclaimer: I know most frameworks only claim to be MVC, and that the definition/principles of MVC vary from developer to developer. Therefore, I've laid out my understanding of MVC.
How I picture MVC (taken from Martin Fowler):
Make a strong separation between presentation (view & controller) and domain (model)
Controller and view should (mostly) not communicate directly but through the model.
Have views (and controllers) observe the model to allow multiple widgets to update without needed to communicate directly - Observer Synchronization.
In Symfony, the Controller returns a Response, and there really isn't a View class. They sort of combined the two.
My questions are:
Is it possible to separate the controller into a controller and view?
Can you make the controller not return something?
Possible to not have any html/templates within the app/bundle?
As I stated earlier, I want to keep frontend completely separate, therefore, I wouldn't use twig. I would use JS, SASS, React, etc. for my frontend stuff to make ajax calls to my Symfony api.
What you are trying to do is a pretty standard architecture.
You do not need to use templates but your controllers have to return "something". If you are handling the view in the front-end, this would be just the data needed to create this view, usually in the form of json
Symfony can do this, no problem

Should interactions to an external api be a model or a controller action?

Currently building an API that pulls data from another API.
I'm just a little unsure about how I should represent some data considering the whole skinny/fat model/controller argument and I haven't been able to find a clear answer so I was hoping for a discussion on this here.
As Models represent interactions with data it feels like my calls be mapped into a model using something like Fractal or Jenssengers "Laravel Model".
As currently I have actions in my controller that send send requests, but it feels like this is a bit too much responsibility for a controller.
So I just wanted some opinions on where I should place this logic in regards to a Laravel project!
Thanks
EDIT:
From further research it looks like the repository design pattern may be a possible solution!
Repositories Simplified
Using Repository Pattern In Laravel 5
Neither method is particularly a great solution. Really, a Controller is responsible for handling the HTTP requests and your models are representations of your business domain. So where does third-party data fit into this?
Well, the data itself should probably be represented by a model. However, the method of getting the data from the third party provider should really be delegated to a service provider that you can then easily switch out to work with different apis and thus decoupling yourself from a single provider (easiest example would be payment gateways, having all of your logic hard coded in your Controller for a Paypal integration would make it extremely difficult to then later add a second payment option).
Take the following example; let's say you have an application that provides a user with the latest results for their favourite football teams.
Your application could have the following endpoints:
/team/{team}/players
/team/{team}/fixtures
/team/{team}/results
These could map to the following controller methods:
PlayerController#getPlayersInTeam($team);
FixturesController#getFixturesForTeam($team);
ResultsController#getLatestResultsForTeam($team);
Notice there are three different controllers, rather than one single controller. This way you can assign a controller to the type of model you're expecting to return to the user.
Now obviously, you shouldn't do your API calls within each controller. But, why would you then do it within your model? The term 'Skinny controllers, fat models' is such an anti-pattern that it really does a lot more harm than good.
Why not use a service that is solely responsible for getting data from the API for your models?
interface FootballTeamData
{
public function getPlayersInTeam(Team $team);
public function getTeamFixtures(Team $team);
public function getTeamResults(Team $team);
}
Now, you can implement this contract and easily switch the way that you get your data from third parties without having to touch your models - which is your business domain, and therefore shouldn't be so highly coupled with the third party API.
You're also now benefiting from skinny controllers, and skinny models. There's no reason why a class can't exist that has just a few lines of code, neither should be fat.
Good luck!

Send Push from CakePHP

I need to send a push message from Urban Airship. To do this I have to send an API request from CakePHP.
My question: where should i put the code for the API request in CakePHP? In the model or in the controller? Where is the correct place for this?
I follow Neil Crookes' idea of keeping the logic in the datasource. An API is really just a datasource, after all. Then, models are introduced as the various endpoints the API has. For example, I have a Stripe plugin that follows this model. A StripeCustomer model then has a $path variable that the datasource uses as the endpoint.
This model has several benefits:
API calls are integrated with the ORM - so they look like regular model finds and saves
You can utilize built in validation, callbacks, behaviors, etc.
Very DRY and therefore easy to debug and test

Implementing OOP PHP with AJAX, MVC?

I'm new to the OOP paradigm (and AJAX/jQuery), but would like to create a basic site employing MVC architecture, in PHP, with AJAX functionality. I drew up a brief diagram of how I currently 'understand' the architecture.
Presumably when AJAX is used, that acts as the controller to interact with the model directly to retrieve whatever functionality is needed? The filenames I added are just to give you an idea of what I 'think' should be included. e.g. index.php would be a html/css template with includes to modules in the relevant places (whatever they may be) - news.php, navigation.php, etc. database.php/pager.php might house the classes and extended classes that I create for pagination, or connecting/querying the database I'm struggling to see what the controller component could be - it'd surely end up being a 'second back-end view' - calling the classes from the model to be sent to the view?
I've probably portayed my confusion well here - what should go in the view, controller and model... is AJAX functionality technically another controller? Any diagram similar to my one above would be extremely helpful.
OK so AJAX is a transport method and not a piece of application like a model or controller.
Your client will communicate through AJAX with one or more Controllers.
These Controllers use or invoke Models to handle different kind of tasks.
Then either the controller or the model responds to the request either with a message in a transport-friendly format (JSON, YAML, XML) or with a View (piece of HTML).
The controller handles requests, that means it receives the initial client-input. Depending on the situation this input has to be formatted, normalized, mutated or transformed somehow before being used in your application.
Then a controller uses or invokes a model; this means that it either deals with business logic itself (old style) and makes use of the model to access datasources or it hands the main workflow of your application completely over to the model (new style).
A model in first instance abstracts a persistent storage entity (like a database). In contemporary application design it also does the main business logic of your application.
There's one way to see this.
Ajax is the medium for sending data between MVC components like HTTP POST. In this respect it does not show up in the MVC pattern.
The actual display in JSON format can also be seen as a view if it's actually used to show data.
From this you should be able to come to your own conclusions.
You can use PHP's best MVC architecture called "YII".Get more info from here
http://www.yiiframework.com/

Categories