Designing an application around HMVC and AJAX [Kohana 3.2] - ajax

I am currently designing an application that will have a few different pages, and each page will have components that update through AJAX. The layout is similar to the new Twitter design where 'Home', 'Discover', and 'Connect' are separate pages, but interacting within the page (such as clicking 'Followers' or 'Following') uses AJAX.
Since the design requires an initial page load with several components (in the context of Twitter: tweets, followers, following), each of which can be updated individually through AJAX, I thought it'd be best to have a default controller for serving pages, and other controllers with actions that, rather than serving full pages, strictly handle querying the database and returning JSON objects. This way, on initial page load several HMVC requests can be made to gather the data for each component, and AJAX calls can also be made to update each component individually.
My idea is to have a Controller_Default that handles serving pages. In the context of Twitter, Controller_Default would contain:
action_home()
action_connect()
action_discover()
I would then have other Controllers that don't deal with serving full pages, but rather components of pages. For instance, in the context of Twitter Controller_Tweet may have:
action_get()
which returns a JSON object containing tweets for a specific user. Action_home() could then make several HMVC requests to get the data for the several different components of the page (i.e. make requests to 'tweet/get', 'followers/get', 'following/get'). While on the page, however, AJAX calls could be made to the function specific controllers (i.e. 'tweet/get') to update the content.
My question: is this a good design? Does it make sense to have the pages served through a default controller, with page components served (in JSON format) through other function specific controllers?
If there is any confusion regarding the question please feel free to ask for clarification!

One of the strengths of the HMVC pattern is that employing this type of layered application doesn't lock you into a workflow that might be difficult to change later on.
From what you've indicated above, this would be perfectly acceptable as a way of serving content to a client; the default controller wraps sub-requests, which avoids multiple AJAX calls from the client to achieve the same goal.
Two suggestions I might make:
Ensure that your Twitter back-end requests are abstracted out and managed in a library to make the application DRY'er and easier to maintain.
Consider whether the default controller is making only the absolutely necessary calls on each request. Employ caching to avoid pulling infrequently changed data on every request (e.g., followers might only be updated every 30 seconds). This of course depends entirely on your application requirements, but if you get heavily loaded you could quickly find your Twitter API request limit being reached.
One final observation: if you do find the server is experiencing high load and Twitter API requests are taking a long time to return, consider provisioning another server and installing a copy of your application. You can then "point" sub-requests from the default gateway application to your second application server, which should help improve response times if the two servers are connected by a high-speed link.

Related

Should views be rendered by the app, or should a static site contact the API using AJAX?

I am starting to write my first web app with Node.js and Express. I have two approaches in mind.
Create two sets of routes. One that sends JSON, one that renders the page using a templating engine
Create a static website that makes API calls to the backend using AJAX, and have only routes for the API.
I understand that approach #2 depends on AJAX support in the browser, but if this was your project, based on the advantages and disadvantages of each approach, which would you choose and why?
If I am reading it right, both options #1 and #2 first set of routes is an API that returns JSON rather than sends it.
Assuming that in #2 you wouldn't create static pages with JavaScript doing AJAX calls, but rather still use express static routing like app.use('/', express.static(path.join(__dirname, 'dist'))); the difference between 2 approaches isn't that big.
Unless you already know some supported template language, such as mustache the cons are that you have to learn one and before that pick one (which isn't always an easy task from my experience!).
If you don't know one, depending on your application, you might still benefit from learning and using one. As an example you can think of a very generic UI where a single template could be reused very many times - like a generic database UI similar to, say well known phpmyadmin.
In case of static routing, you can achieve similar results by using a JavaScript framework which has components or templates, such as angular. If you aren't planning to use one, that could result in a lot of code duplication of otherwise re-usable widgets. And even when using one I can imagine a case when template engine would result in less code (or less files in your project at the very least). Not sure though if it's going to be easier to navigate and moreover to cover with tests when the project grows.
Without knowing more about your project it is hard to give more advice.
If the product you're developing is primarily static content with some dynamic pieces here and there, I'd recommend serving HTML from your backend via a templating system. A good example of this would be a blog. You'll end up with better SEO and there are less moving pieces to grok in this approach.
However, if you want to develop a single page application, I recommend using your backend entirely as an api, and writing your client side logic entirely in React/Vue/Angular/whatever. Single page applications have their front ends written entirely in javascript, and are best suited to highly dynamic, "app like" experiences online. Think gmail or facebook.
In my current project we use both approaches. Many views are static and data is obtained from API calls (we just use angular) or bootstrapped values (we load some objects with template, like user roles etc.)
However, some views are rendered on server site, because it easily allow us to dynamically inject values, tokens or other supporting data without making extra requests.
So, I vote for flexibility

Having multiple AngularJS apps for one site?

I am developing a site that can be broken down to a handful of main pages. These pages can be thought as isolated from each other, except they share the session data (ie. session id and logged-in username).
Initially, I was gonna build the site as a SPA using ng-view (ie. make the pages into AngularJS views). But then, I don't see any benefits for my site to be implemented in that way. And it would require extra time and efforts to make it support SEO (Making AJAX Applications Crawlable).
Going with an approach that does not provide any benefits and even creates extra workload doesn't seem to be too smart. So I thought to myself, why don't I make the main pages of my site into individual AngularJS apps. The parts of the site that need to be indexed by search engines are simply the initial screens of some of those apps, so I wouldn't need to do extra work for SEO. (Note: The initial screens are rendered by the Django server with data for search engines to crawl, so they are non-blank.)
For each of the apps, it may or may not have its own set of partials, depending on the requirements on it.
Example:
mydomain.com/item_page/1234 (load "item" app)
mydomain.com/dashboard (load "dashboard" app)
mydomain.com/account (load "account" app and default to "tab_1" view)
mydomain.com/account#tab_1 (load "tab_1" view of "account" app)
mydomain.com/account#tab_2 (load "tab_2" view of "account" app)
mydomain.com/post_item (load "post" app)
This is solely my random thought and I haven't seen any AngularJS examples that are comprised of multiple AngularJS apps. I would like to know:
Is the multiple-AngularJS-apps for one site approach feasible? What are some caveats that I should be aware of? Are there any example site out there in the wild that's taking this approach?
If feasible, how do I share the session data between the apps?
Note this post is about multiple AngularJS apps for one site, not multiple AngularJS apps on the same page.
There is nothing wrong with such approach, as long as you keep the size of downloaded JS script small enough, and ensure good caching. One of examples of such applications can be GitHub (they are not using angular, but approach is the same). When you go Issues page on GitHub, it loads an html page, common Github JS libraries and page specific JS code. Navigation and actions inside page, are handled by that single page specific script. If you go to other section (like Code) a new page with new page specific JS code will be loaded. Another example is Amazon AWS console, they even use different frameworks for different pages. (both GitHub and Amazon don't use Angular, but this approach works for any JS based framework, even for GWT).
As for sharing some session data between pages, you can embed this info directly in the page itself, using inline scripts or hidden elements. E.g. when your server is generating page, it should also generate some session information into the page. Another approach is to download session data once, and store them in local storage/session storage.

All-js or initial markup by the framework

Ever since I've started asp.net mvc development my experience is almost 80% jQuery, only 20% C#.
Now I am begginning to use Knockout.js to enable myself to better control view on the page.
The question I am now facing is: should I be feeding the browser the "sceleton markup page" and load all data via ajax call, which in turn populates a js viewmodel object and therefore the view, or should I initially populate data via a partial view, and use js page data management for subsequent client experience?
Right now I am doing the latter, but this requires me to write two data retrieval/display logic - one in js, one in mvc razor view.
I am not planning to support browsers with js disabled, so maybe I should do everything via js knockout view model initialization?
There are many additional variables.
How many request per second should your app handle in future? If many, then with full page generation maybe you can cache resulting web page, decreasing load on server.
What kind of clients do you have? If they are slow (like low cost mobile phones), then generating full HTML on client can be slow.
Do your clients appreciate fast response over slow network? With full server page generation you can achieve smaller number of requests and faster response.
On the opposite side, if this is an internal department level business app with good network, low number of requests and good client computers, then you can surely go with minimal initial page and populating everything with AJAX. Also, as Arbiter pointed out, JSON can be smaller in size than HTML, so if you have a big amount of data then you can save on network via JSON.
There is also a middle third way. You can generate JSON data and embed them directly in the webpage (like <script>CallMyJSGenerateMethod({generatedJSON: "goes here"})</script>). This way you'd have only one (JavaScript) procedure for HTML generation, small number of requests (with even lower amount of data) and ability to cache web page. Still, you'd have to have a good clients, so point 2 still stands.
This is more of an opinion, but in my estimation, its the most oft asked question I get regarding building web apps: do I build the pages with HTML/MVC on the server or do I use all JS? There is no clear right answer here that fits all scenarios. Both are great choices. Dmitry's points are all valid, too.
Other things to consider are whether you need to stick with ASP.NET on the server or if other server tech will be used (PHP?). What skills does your dev team have? Will the pages you are creating change a lot on the client, or are they relatively static?
I personally lean towards the client space instead of server side generation, but its mostly a preference.

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.

How to maintain state in a web app - as HTTP is stateless

I am new in building web apps and just begun learning and setting up Grails. I am planning to build an app which has a flow of 4 to 5 pages. Since HTTP is a stateless protocol, how is the state between the pages maintained usually. I am curious what is the accepted standard here, should I create session scoped objects and use them between pages or keep passing around the values between pages (not sure if it is effective if I have a large number of items on a page). Or instead of using 4 to 5 pages should I just use one page with multiple divs and show/hide based on the user clicks?
I think using domain objects in Grails would help here but I dont have a DB backing the UI and only some webservices which will do the UI actions so I cant use domain objects.
A Grails specific solution would be good but also wanted to know how this is handled in web development in general.
Without using a DB, there are a few options you could use:
Use POST/GET variables to pass info from page to page.
Use the session to store information.
Use cookies to store information.
Using POST/GET is usually best if you just have one page "talking" to one other page (e.g. submission of a form). If you have a bunch of data that will be shared by several pages, the best way to do it would probably be to put them in the session. If you need those values to stick around after the user leaves your site and comes back later, then you might want to use cookies.
You may want to look into WebFlow (Spring WebFlow) in Grails. I find it helpful in wizard like or shopping cart like applications where you want to hold on to the data between a group of pages (ie: Page 1, Page 2... Page 4) and then at the end submit the data somewhere etc.

Resources