Laravel Web and API controller structure. Separate vs DRY - laravel

I want to build a Laravel application which users both web and API parts. The common (and mine as well) question is whether to use separate controllers or not.
There are 2 options:
Separate controllers
Laravel API controller structure?
Use one controller and check the request type (is Ajax, or depending on the request link) and return either JSON or HTML.
Laravel resource controllers for both API and non-API use
Those who have the 1-st opinion doesn't explain the DRY problem solution - web and API controllers would be the same except the return statement (JSON or HTML view). But since most post recommend to separate controllers I suspect I don't understand something about the DRY problem solution.
I don't see any disadvantage of the second method. But people say something like
If you use only one controller, you will end up soon with a messy class with thousands of lines. Not only this is not going to scale well, but it will be hard to work with for you and your teammates.
Please explain me the DRY problem solution for the first approach (separate controllers) and the possible underwater rocks in the second approach (single controller)
Please explain which approach is preferable.

I think this is a great question, and I too am keen to see the responses.
I can see the arguments for both approaches. I however would create and maintain separate controllers, whilst using services to share common logic between the controllers where it is known that this will never change.
For example, if you allow users to upload avatar images. I would put such logic in a service and consume this service in both controllers.
The reason for this approach in my mind, is that the web and API logic may diverge and it would therefore be easier to iterate each without impacting the other.
If this is unlikely, then I would still create separate routes, but point them both at the same controllers, so that if it did change in the future, you can simply re-point the API routes to their own controllers.

Related

Where Do I Create External API functions or Classes? Proper MVC Structure for Web Frameworks

I am looking to add multiple API's to my senior project on an MVC based framework (Laravel). I understand the basic concept of MVC, but want to make sure that I am doing things according to best practice.
Basically, I am going to have a class/function that takes a query and calls that query on a Amazon's Product API. I have seen an example of calling API's from directly within the Controller on Laravel (see http://www.phplab.info/categories/laravel/consume-external-api-from-laravel-5-using-guzzle-http-client).
Perhaps I don't understand MVC well enough. Should an external API call be in it's own class? And if so, should it be a Controller Class or a Model Class? I hope the Stack Overflow gurus can enlighten me. Let me know if I need to clarify anything!
It depends to what you want to process with external API.
If it's a part of the business, it can be in Model (lot of people put
the business inside the model to follow the encapsulation principle
of OOP).
If it's the explicit process, it should be in Controller
(like most people do).
For example, if you have a model Transaction in bank transfer (that automatically convert the currency, it needs the external API to get the exchange rate), the external API call should be wrapped in model. So controller cannot modify the Transaction object and it will be safe.
In another hand, you can call to external API in controller, do some extra stuffs then set it back to Transaction object. It's also good because model always contains only properties. It makes application also clear enough.
They are 2 ways of use, none is absolutely right or wrong. But if you choose one, follow it, don't mix.
Another, both 2 are only ok. The better way is putting the external calls to other places (modules etc), then call it by single line in model or controller.

Where should we put the authorization code? FormRequest, Policies, Controller, Middleware...?

Where should the authorization code in Laravel? We have a lot of options and a lot of plugins to manage this situation but and I'm not really sure where I should put all logic. Let's see:
I know that there are a lot of possibilities with a correct result but I want to know which is the optimal solution for you or know your techniques in this situations.
Imagine we have a help desk application done in vuejs and Laravel as API, so we have users, groups, roles, permissions. And maybe a user will only able to see its tickets.
Should we do a TicketPolicy with view, update, create methods? Maybe should we use repositories? Maybe a is_user_allowed method in Ticket's model?
Should we use middleware in routes files and do something like Route::get('tickets/{ticket}', 'TicketsController#show')->middleware('can:show')? Or should we call $this->authorize($ticket) in show, edit, update and store methods of the controller?
Or maybe should we use FormRequest#authorize method and then use something like $user->authorize('show', $ticket)?
What if we want groups or roles? Should we use some plugin like Entrust and/or policies?
What do you think, what do you do?
Best place I found to put classes that group specific logic that do not fit in standard MVC pattern is completely new folder for Laravel. I name mine Services, probably because I read it somewhere. One of the great things in Laravel (and probably other modern frameworks) is flexibility, you can just pop a folder, add a new namespace and have it contain whatever you need.
As for your example, I would implement a class App\Services\Permissions that would contain all necessary logic for accessing different resources in your application. Then call it's methods wherever you need them, be it Requests, Middlewares or Eloquent Models.

SPring MVC - Several Controllers

I am developing for learning purposes my very first "big" Spring MVC project. I am learning everything by myself (and of course, thanks to this amazing community).
What I am starting to wonder is... Is my design "correct/valid"? So far I am creating one Controller per View/Page specially because of the ModelAttributes (attached to the method).
Is that fine? Should I start doing it in some other way? Are there "offical" patterns in this matter?
To start, I assume you are creating a web project based on your use of ModelAttribute. You want to follow the MVC (Model, View, Controller) convention. The "Model" is the data you are manipulating. This data should be retrieved via a service layer. Then, your controller should call your service methods to get the data, making your controllers completely agnostic of your data. This is nice because you are free to change your data structure, e.g. migrating from MySQL to MongoDB, without worrying about changing your controller, all you need to change is your service layer. Also, this allows for controllers to use many different services in certain instances. Your controller receives requests from the client, e.g. the website user's page requests, GET/POST requests, etc., and performs some action, usually fetching/updating data via the service layer, and then returns a view. Each controller can take many requests, and can render many views. It is good practice to break up controllers by function. For example, if you had two different sections for your website, one for Admins, and one for Guests, then you may want to use one controller to process the Admin requests, and another to process the Guest requests. Each of these controllers can handle all requests from Admins/Guests accordingly. You may be a bit confused about controllers. Each method in a controller is bound to a single request/view, but a controller may have many such methods.
As you are learning, I would suggest exploring some client-side mvc frameworks like AngularJS. Angular allows very easy data binding and manipulation options, and makes it pretty easy to create RESTful web services.

Controller in Backbone.js

I'm new to Backbone.js. I have gone through the documentation. My question is
where does the controller concept come into picture? In other words, what is a controller in Backbone.js?
I heard that the router is the controller. If so, why it is considered as a controller? Can we develop simple basic apps without the Router also? In that case what will be the controller?
To clear things a little bit here. A Router is not a Controller, It's a way to define a client-side route map (similar to Rails's routes.rb). This helps routing client-side pages to certain actions/handlers. And that's different from a controller's job which is to provide a bit of orchestration between Models and Views. And there is actually more than one way to do this using Backbone. Quoting from Backbone's documentation:
References between Models and Views can be handled several ways. Some
people like to have direct pointers, where views correspond 1:1 with
models (model.view and view.model). Others prefer to have intermediate
"controller" objects that orchestrate the creation and organization of
views into a hierarchy. Others still prefer the evented approach, and
always fire events instead of calling methods directly. All of these
styles work well.
This brings three different approaches to accomplish this. The first one is pretty straightforward which is to have the model object included as a property to the view.
The second one proposes including a third component that performs this role of orchestration. I believe this can be helpful in quite large and complex applications. For this I encourage you to look at Chaplin, a sample application architecture using Backbone.js. The guys have done a great job in separating things out and also introduced the concept of a Controller into the architecture.
The last approach is suggesting using events to mark for actions and mediator to handle these actions. For this I encourage you to look into the mediator and Publish/Subscribe JavaScript patterns.
Check out Addy Osmani`s article on MV* on the client:
http://addyosmani.com/blog/understanding-mvc-and-mvp-for-javascript-and-backbone-developers/
From the article:
In Backbone, one shares the responsibility of a controller with both the Backbone.View and Backbone.Router.
and
In this respect, contrary to what might be mentioned in the official documentation or in blog posts, Backbone is neither a truly MVC/MVP nor MVVM framework.
It's more similar to how for example iOS Cocoa Touch framework works, you shouldn't think about it like a backend MVC, backbone team itself even never mentions MVC on their website to avoid confusion people often have when coming from backend MVCs. The View in backbone is what's called in iOS a ViewController/AppController and usually your main AppController will be a View which sets the main wrapper for your application which usually you would also use as a global pub/sub system and controller for your main app logics.
Router is exactly what it say - it converts routes into set of params and passes them to the app controller to figure out what to do with them, what subview to load etc. (or if application is less sophisticated it can load/change the views straight from the router level) - It used to be called controller but it was renamed in (0.5 I believe?) to clear this confusion.
At least this is our approach - if you checked multiple tutorials in the wild you've probably seen that when it comes to Backbone there are as many approaches to this as many developers there are. And that's what is beautiful about Backbone! :)
Usually I make my own controllers, and let the router do it's thing (catching routes, and pointing towards a controller action). These controllers are home made, just javascript objects with methods on them. They take the request from the router, collect the right data (collections, models...) and take the necessary view, combine them and pass the data into the view.
from there on it's backbone again.
however recently I came arcoss a 3rd party backbone plugin called backboneMVC. Have read it's documention, but have yet to try it out myself.
It aims to take over your router and make routes based on your controllers and actions you define with it.
Take a look at that library however I cannot promise anything because I have yet to build something with it myself.

Coldfusion, whats the advantage of front controller design over page controller?

I'm from a non-computing background and I'm struggling to getting my head around MVC design approaches and frameworks in general. I "get" code re-use, and separation of logic from display, and I "get" encapsulation and decoupling, but I don't get this.
At the moment I simply put everything in root, a separate subfolders for images, cfcs, and _includes, all database interaction via cfcs. I do all my processing at the top of the page, then a comment line then display/page layout below that.
Most of the frameworks I have looked at seem to favour a front controller, so my simplistic version of a top controller MVC design would be a subfolder for cfcs, controllers, and views and a big switch statement in index.cfm
<cfif not IsDefined("URL.event")>
<cflocation url="index.cfm?event=home" addtoken="No">
</cfif>
<cfswitch expression="#url.event#">
<cfcase value="home">
<cfinclude template="controllers/home.cfm"/>
<cfinclude template="views/home.cfm"/>
</cfcase>
<cfcase value="about">
<cfinclude template="controllers/about.cfm"/>
<cfinclude template="views/about.cfm"/>
</cfcase>
</cfswitch>
.. but what real advantage does that give me over a page controller design? Unless it's just the kind of sites I write, I always seem to find that the controller logic is specific to a view, its not like one controller could fit several views or several controllers could output to one view, so what would be the point of separating them?
The light hasn't come on for me yet, any pointers?
By "top" controller, I think you mean "front" controller, a single point of entry for requests into an application. As #bpanulla wrote, most ColdFusion frameworks use this design pattern. This becomes particularly interesting with URL rewriting, where it becomes easy to have search engine safe URLs by intercepting the a URL (e.g. domain.ext/i/am/friendly.ext) and routing it to some standard file such as index.cfm while making the requested URL a parameter (often as a request header). This also makes site redesigns where URLs change easier because it lends itself well to aliasing or redirects.
As far as controllers are concerned, they are usually tightly coupled to a particular URL or URL pattern. It's possible be more loosely coupled with controllers, but in practice I find that's an emergent property after multiple refactorings. What should be underlying the controller is one or more calls to a service layer that talks to the database, executes business process, creates stateful entities, etc... Then the controller receives the service layer's outputs and places them into whatever mechanism (e.g. an event object) is used to pass data to the view(s).
It's the service layer that's meant to be reusuable not the controllers. The controllers are merely an extension of whatever framework an application works within. The idea being that you should be able to switch frameworks with very little impact to the views and service layer. The piece that needs to be touched are the controllers.
So a given service object in a service layer should be able to service multiple controllers. For example, consider showing a logged in users' information as a widget on a site. There might be different pages served by different controllers, but each would call the same service object to get logged in user data that presumably might be given to the same view that renders the widget.
Update: Front Controller Advantages
Security: centralized authentication and authorization.
i18n & l10n: inject the right language pack into the request globally
Process Orchestration: think multi step checkout process for a shopping cart where you don't want the back and forward buttons to work - by routing everything through the front controller you're able to enforce what step (i.e. the state)
Logging & Tracking: easily add Google Analytics or other request tracking to a site by making the addition in just one place
Error Handling: centralized behavior
Now many of these items can also be done using <cferror> and Appplication.cfc, but I find it easier to have one centralized point.
Useful Links
http://java.sun.com/blueprints/corej2eepatterns/Patterns/FrontController.html
http://msdn.microsoft.com/en-us/library/ff648617.aspx
You actually implemented the crux of Fusebox (http://www.fusebox.org/) with what you wrote. There's nothing wrong with that, and most of the ColdFusion community used something similar to that for many years - Fusebox was the most-used CF framework (in my experience) until just a few years ago when ModelGlue, Mach-II and the other second generation CF frameworks came about.
One thing I can point out is that your approach to controllers (as .cfm files) actually does not enforce encapsulation in the typical OOD fashion, with specific arguments going to an object method call. Unless you are extremely dilligent, over time your .cfm controllers may wind up accumulated a large number of undocumented parameters that alter behavior to solve one problem or another.
With the various frameworks you also get nice features like Application, Session, and Request specific code (onApplicationStart, onRequestEnd, etc). But you can always get those through a simple Application.cfc.

Resources