Coldfusion, whats the advantage of front controller design over page controller? - model-view-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.

Related

Laravel Web and API controller structure. Separate vs DRY

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.

Layered architecture mvc

I'm creating a web app using an MVC framework. I thought of adding a layer between the controller and the domain models, I think it's called application layer in DDD, to avoid putting logic that is specific to a certain use case in the domain models.
The controller will only interact with this layer and this layer will orchestrate the operation using the domain models. This layer will be kept as thin as possible pushing all the logic that is not use case specific to the domain model.
I will call the classes that belong to this layer DomainCtrl.
Example login scenario:
Model: LoginForm
DomainCtrl: AuthCtrl
UI: ui controller
1.ui controller receives request
2.creates instance of AuthCtrl
3.AuthCtrl creates instance of a LoginForm and fill it with request data passed to authCtrl
4.LoginForm performs the login
5.authCtrl does other things that are specific to this specific way of login -> returns errors to ui controller
Is this a good way to organize an app?
Your question
Is this a good way to structure an app
is a very loaded question. The simple answer is Yes, but the more correct answer is It depends.
Let's start with the simple answer. Having your main application be unaware of the UI is generally a good idea. It means that you can easily consume your application from various places. In DDD this outer layer is usually called Application Layer. It is mainly responsible for orchestrating interactions between your domain, persistence and other resources that you might rely on. This also allows you to have your domain at the center unaware of everything else. This makes your domain easily testable and maintainable if implemented well.
Now the "it depends" part of the answer. DDD is not the only successful way to build an application, and in some cases it might be more of a hinderance than anything else. You have to ask yourself what is my app doing. Are there many domain specific rules? Am I only fetching and storing basic data etc? These are all questions you need to answer before you choose an architecture and technologies.
I would still say you probably won't go wrong by choosing the DDD approach as it is generally a good way to do things.
*Note: Your example is not that clear to me but you should be careful of spilling UI concepts into your domain/application. A login form is completely a UI concept as is auth to a certain extent. You can probably have your application return the details of your user, but the UI layer should decide if the user is allowed to proceed or not.
At a high level view, Yes
But it ultimately depends on "how" you logically separate your layers. In your scenario, I don't see any application layer.
I assume AuthCtrl is the domain? Who creates AuthCtrl? what layer does it exists?

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.

Use client-side MVC/MVVM patterns with MVC server-side pattern

Considering the most popular MVC/MVVM client-side patterns (like Knockout.js, Angular.js, Ember.js, and others), I have one great doubt:
Also considering the modeling redundance in both sides, what is the advantages and disvantages to use those client-side patterns with MVC server-side patterns?
I struggled with how to answer this question... hopefully this helps, even if it is in a round-about way.
While some of the pros/cons have already been stated, I think the best rundown is in this answer.
For me, the biggest advantage to using client-side logic is the rich UI aspect.
But the key part of your question seems to be "model redundancy" (I'd call it duplicated logic, or at least having potential for duplicated logic). In my opinion, that is a problem which may exist independently of the pros/cons in the previous link.
So first of all, I think that the decision of whether or not to use a client-side framework should be made based on the well-documented pros and cons. Once that decision is made, the associated problems can be solved.
Lets assume you are using some sort of server-side framework/platform, as well as a client-side framework to provide a little bit of UI interactivity. Now there is a problem with where to put the model logic: on the client, server, or both.
One way to solve the problem is to define your model logic in only the client or the server. Then you have no code duplication, but it affects some of the higher-level pros/cons.
For example, if your model logic is 100% server-side, you lose some of the interactive part of the UI. Or, you are constantly throwing the model to/from the server, which will have a few cons.
If your model logic is 100% client-side, you could suffer performance problems, depending on the size of your view / model. This is one of the reasons Twitter is moving to a server-side processing model.
Then there is "both"... having model logic exist in both the client and the server. I think this is the best solution, as long as no logic is duplicated.
For example, on a shopping cart page, you may recalculate the cost of an order based on the price of a product, and a user-editable quantity box. I think this logic should only exist on the client. Other model properties that do not change once loaded are probably fine hosted on the server.
There's a lot of gray area here... I struggle with putting all the eggs in one basket. For example, choosing a client-side framework, creating a lot of client-side logic, and then [hypothetically] running into problems with performance, browser support, or something like that. Now you may want to tweak a page or two for performance (like move it server-side, a la Twitter). But I think being smart about how you structure your code will help mitigate that issue. If your code is maintainable and clean, moving logic from client to server won't be difficult.
The advantage is that the client side patterns are applicable at the client where the server has no direct reach. If you're building a rich, interactive HTML UI then use client side MVVM. Server side MVC may still be relevant in that case for delivering appropriate content to the client. For example, the ASP.NET WebAPI is a framework for creating HTTP APIs which has a similar controller architecture to the ASP.NET MVC framework. The API implemented with this framework may be called by client side code resulting in MVC on the server side and MVVM on the client side. Normally, when using MVC server side and MVVM client side, the responsibilities of the respective sides are very different and thus there is no redundancy.
The fact you an incorporate a MVVM model into an already implemented MVC framework is also a great thing, we recently added knockout to some new project pages to fit with in an already outdated MVC framework (old pages, not the framework itself).
I think MVVM is fantastic as the above answer states it provides an exceptional user experience with extremely fast response times, you can hide your validation calls in the backround with out slowing them down and its intuitive.
The pain however is that it is VERY hard to unit test and you can get some extremely LARGE javascript files, also the extra coding we've had to do as our legacy systems still run on IE6 is ridiculous.
But MVVM and MVC don't have to be used exclusively on there own, we use both. But having 3 levels of validation is something that still bugs me.
advantages
This can rock.
disvantages
You can screw it.
Seriously. Making use of transporting part of the frontend logic into the browser can boost your application development why you keep more strict data-processing encapsulated on server-side.
This is basically layering. Two layers, the one above talks with the one below and vice-versa:
[client] <--> [server]
You normally exchange value objects in a lightweight serialization format like Json between the two.
This can fairly well map what users expect in a useful structure while domain objects on server-side could not be that detailed.
However, the real power will be if the server-side is not in written in javascript at some certain point because I think you can not create well domain objects there. Consider Scala (or something similar expressive) then if you run into that issue.
Ten months later after this question, I have used the both patterns inside the same application.
The only problem was the need to map the models twice.
MVC (ASP.NET MVC 4 Web API)
The most important resource was the routes.
Models were created to database interactions and as arguments for
controllers' actions.
Controllers were created to manipulate the API
requisitions and to render the views.
Views were not modeled with
server-side models, but all the resources of Partial Views and
Sections.
MVVM (Knockout.js)
Models were created with the same properties as the server-side models.
Views were binded with models' properties, and decreased a lot of the views' size.
View-models were created with the values provided from API methods.
Overall, the MVC combination with MVVM were very useful, but it needed a big expertise and knowledge. Patience is required too, because you need to think about the responsibilites of each application layer.

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.

Resources