RESTful API design pattern while creating API with php - php

I am developing RESTful with php. Currently I have started coding with MVC design pattern. In which the view files are acting as an interface. An interface which isn't showing any graphical UI but it has all the request handling logic.
Now, my question is the way I am coding is correct or there is a better way to create RESTful api in php?
My inspiration is based on JavaEE application model. In which we have Entity classes as model, Java beans as controllers and Remote Interface is the the list of method which gets called from client (kind of a view).
Am I on right track?

A good example for building a RESTful API in a PHP based MVC framework can be found at http://www.chrisdanielson.com/2009/09/02/creating-a-php-rest-api-using-the-zend-framework/.
This example extends a class in Zend Framework called the Zend_Rest_Controller which simplifies this process. You can have a look at the source code to see how they do it and if it gives you an ideas on how to make your own implementation.
To answer your question though, you should have controllers acting as the interface. So if you send a POST request to myapp.com/comment (where comment is the controller), it knows you are trying to add a new comment. If you send a GET request to the same URL, it knows you want all of the comments, and if you send a GET request to myapp.com/comment/4 it knows you want to get the comment with ID 4. Your views should have nothing to do with the internal functionality of your API.

You can use any existing RESTful PHP MVC framework, like Yii or Kohana both are very light and natively support RESTful applications.
For your existing application, MVC model states that all the requests and logic handling should be done by the Controllers not the views. Things are usually done in one of two ways here:
(1) Controller has a special method to respond to each type of requests and acts differently As seen in RubyOnRails (mainly at the end of each controller action)
respond_to do |format|
format.html
format.xml { render :xml => #events}
format.json { render :json => #events}
end
(2) Controller detects the current requested format and changes that entire theme/layout to, say, a JSON theme (All layouts/views receive the same data). This is my current implementation and it goes like:
$format is any of [html,json,xml] (detected from url suffix)
$controller->layout = "$format";
$controller->render($viewFile, $object);
view file in HTML Layout
<div id='model>
<h1><?=$object->title?></h1>
<p><?=$object->description?></p>
</div>
View file in JSON layout
echo json_encode($object);
View file in XML layout
/** Loop and build XML tree */

I did a bunch of webinars on API Facade Design Patterns. Hope you will find the concepts useful irrespective of the underlying technology you use to implement it. Please can find it here
http://youtu.be/n8B-K3iJ7b4
http://youtu.be/MRxTP-rQ-S8
http://youtu.be/aJBhVm4BbCI

Apigility is a Zend Framework 2 based project designed soley for the purpose of creating REST and RPC services.
https://apigility.org/
Out of the box you're given an easy way to get started with MySQL and OAuth2 for authentication.

Related

Is this really the MVC design pattern or should I call it something else?

This is a question about theory, so there is no need for code snippets.
I built a router that, as a typical router does, dispatches a controller based on the URL. The workflow is something like this:
Router dispatches controller and instantiates it
Controller renders a view
User interacts with the view
Controller updates model based on user interaction
Model returns the new state of the data to the controller
Controller updates the view based on new data
So basically, the controller is the starting point and the link between the model and view. The model and view never directly interact with each other. The controller is the workhorse and has most of the code.
Now, that is all good and I get it. The confusion comes when I read articles about MVC design patterns and realize what they describe is not what I just described above. It seems like, in the pattern you start at the view. The view talks directly to the model and the controller accepts user interaction to update the model.
So, what I'm doing may involve models, views and controllers, but its not strictly the MVC design pattern. I did read one article where they called what I first described as CAV, controller action view.
My question is, what is it that I'm describing? I don't want to keep referring to it as MVC if its not actually MVC. From what I read true MVC was birthed in the 70's. Things have changed since then. Perhaps what I'm doing is some evolved version of MVC, but not MVC in its strict form. Is there another name for it so I can stop confusing myself, and others, by calling it MVC?
I think its language (technology) dependent.
You tagged your question with the php tag, so I suppose you're developing applications using this language. In a classic PHP application, the view can't get updates from the model (in fact, this more related to the PHP language being executed only on the server).
First, the entire application is launched for each request and is terminated when all the response has been sent. So, the router is called for each request.
Then, the router execute the controller which have to handle the request (according to routing rules).
The request being for reading or writing does not modify this behavior.
If you want to allow the view to ask for data modification approval to your controller, you may need to use some client-side programming language (Javascript). So, you may use a REST API to handle communication between the model and the view.
To answer your question, I think you can't implements a pure MVC design pattern on a client-server model without using a programming language on the client.
Even I faced this confusion previously. In the original form, View did interact with the controller. They followed the observer-observable pattern. This was how MVC was conceived in SmallTalk. However, The version of MVC that you are talking about is actually a modern version of it and is used in most frameworks. It sort of has became a standard. I do not know of any other term for it. In this version, the controller is actually a bridge between view and model. However, both of the patterns achieve the desired objective of separation of concerns.

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

Yii - Adding RESTFull API to webapp

I have an existing app that was built on the Yii Framework for managing wine cellars. I used the standard Gii utility to create the initial CRUD controllers/models/views. I've significantly modified the code to meet my needs for navigation, look & feel and functionality. I'm now beginning the design for a companion mobile (android) app that will need to consume and create some of the data (get a list of wines in my cellar - GET, add a new wine to the cellar - POST) that can be used while out shopping/wine-tasting. I don't intend to expose all the models/controller options as web services, only a specific set of functions.
My question is really a design issue. Should I add the API methods to the existing CRUD controllers or should I create a new "API Controller" for each of the models (or a single apiController is another option I've seen)? My thinking is separate API controllers. This would allow me to update/deploy API specific changes more easily and to logically compartmentalize that interface. This API will need to be authenticated and I will probably implement OAuth in a future release.
BTW, I've looked at the RESTFullYii extension and I haven't been able to grok exactly how it works. I'd really love to see a working example app not just code snippets.
I suggest you to create a new controller. For example ApiController. You put all your actions such as actionAddWine. So you can call this action like:
http://example.com/index.php?r=api/addWine
The advantage of doing this, is that you have all your models, and you just need to interact with your modes via REST. In order to create a simple REST api you can check the following document which is really simple explained.
How-To: Create a REST API
If you do like the mentioned article, You can send the response to client simply using _sendResponse() method.
Another thing is to do authentications and similar things which can is readily attainable using your controller's init() method.
Another way is to create a module for your application. If you want to completely divide your API from your other codes you can create a module. You can create modules with GII. The advantage of module is that you can separate your sections. For example your actions will be:
http://example.com/index.php?r=api/wine/add
in above url you are calling an action in api module, and wine controller which its name is add.
Note that you can use your models in module by importing them.
Yes, go for separate controllers. You may even want to set up a separate application that shares some of your apps models and config but also allows for a more separate feel.
Also with planning how you will version your Api, as it is likely to need to change down the road while still needing to support your older Android app

Is it advisable to use API based architecture for both native and non-native sites?

I am planning to use a architecture (MVC = PHP->Yii) where I will be using REST API based architecture for native site (main web app) and non-native (apps such as iPhone, BB, WAP etc).
No my question is it advisable to use View-Controller (HTML+User Requests) (For Main Site) with Controller-Model (Request/Response+DB) (for API) and same API platform will be used for non-native apps, or should I use full MVC for main site and build separate platform for APIs. This is because I don't want additional HTTP (cURL) overhead for main site.
Update:
#karmakaze
That's the though with me but still I have to write RestControllers because there is lots of code involved. So anyway we ends up having two different controllers e.g.
UserController extends CController {
actionRegister() {
...Some calculations
.
.
Instead of making Calls to model We will use call controller i.e.
$userRest = new UserRestController();
/*
* This will return json data or php obj depending on params passed or
* may raise an exception
*/
$userRest->actionCreate($param1, $param2);
// Process data obtained.
}
}
or is there any other way around?
If it fits your needs, you may build a front-end based on some JavaScript libraries like AngularJs, BackBone.JS or any other MVC JavaScript library.
This way you should build only one RESTful API in Yii, as the back-end of your app.
This solution, however, lets something uncovered: it will be hard to make the application crawlable.
The perspective of the question made me to understand that it is relatively important to render the HTML on the server side. I am thinking at this solution:
make normal MVC app, including controllers and views
Use any of the following ticks:
a GET parameter that will be false by default, but ture when it is an API call:
Check this example:
// in a controller:
public function actionView($id, $api=false) {
// some calculations, getting the $model variable
if ($api) {
echo $model->json_output(); // you can implement it in components/model.php or generate the json output some other way
} else {
render('view', array('model'=>$model));
}
}
a subdomain called, for instance, api (you'll have api.yourapp.tld),
or use another HTTP parameter from the request to determine if it is an API call or not.
Any of these version will bring a way of verifying if the client requests a JSON/XML response (API call) or HTML for the browser.
This way you avoid the headache of building separate controllers for the API and the main site.
Note It is not required to do this trick for actions when they simply render a form - it is useless.
Note 2 You can use the latter method to render the requests with _request_fragment and assume that every request is an API call unless $_GET['_request_fragment'] is specified. Like this you can make an AngularJs, Blackbone.js app crawlable with Yii.
UPDATE The _request_fragment is specified here, and it is used by most search engines to crawl AJAX web applications.
You can use the same for both native and non-native app, it will also reduce you work at development time as well update or change ur logic.... I do have so many experience with such situation..
Use full MVC for main web app and reuse the same Models and Controllers to build the REST API. There are extensions which will do this automagically if you follow Yii conventions while building the main web app. Just search REST in the Yii extensions. We'll be doing the same for our mobile apps. Currently investigating RESTFullYii.

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