I’m starting now with REST (using Laravel 4.2) and Mobile (Android, iOS, SP, etc.) applications.
Initially I’m checking if the request is ajax/json and then return a json response.
But this condition is in a normal action (HTTP), so:
if ajax/json return json, else return the view/template/layout
Is it correct to do that in the same action, or is the best practice to create another controller for that? For example:
- PostsController
- PostsMobileController
Or
- PostsController
- MobilePostsController (or JsonController) – using namespaces
Although the right solution depends on your context, here is my approach:
When designing classes one should always consider their single responsibility. In case of the PostsController it could probably be described “create, read update and delete” posts. Formatting of the output is a global problem of your application that should not be solved individually in each controller. Better would be to design this as an output strategy / aspect / whatever your language and framework allows.
Just imagine if you need an API for outputting XML at some time. Would you really create new controllers for each entity?
Btw, when considering such questions (for any language) I tend to look at the Rails documentation, which has a nice approach here:
class UsersController < ApplicationController
def index
# Load all users
@users = User.all
# Different formattings based on request headers
respond_to do |format|
format.html # index.html.erb
format.xml { render xml: @users}
format.json { render json: @users}
end
end
end
2
You have outlined the two main approaches, and each have their advantages and disadvantages.
If you combine both in the same controller, and all you are doing is changing the output, then using a single controller makes sense. The logic is the same, but the output changes.
If the logic has to change because the output is different, then go with two different controllers.
Separating them into two controllers also gives you the ability to easily add support for non web platforms, e.g. native mobile applications. Your Larvel app then has two sides: The web side and a data API.
The direction you take will largely depend on the future needs of the application. My advice is to start out simple. Use a single controller that just changes the output format. It’s easier to add complexity later than it is to add simplicity. If you need a data API later, then start adding different controllers after you’ve done some architecture and system design work.
0