Use client-side MVC/MVVM patterns with MVC server-side pattern - model-view-controller

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.

Related

Need help understanding MVC

To my understanding, MVC is a way to implement the separation of presentation tier from business and data tier. Am I understanding this correctly? If so, MVC should separate the business logic completely from presentation, right?
So to me it seems like javascript (or jquery) is somehow violating the MVC design since it takes over some of the logic on the client side, isn't it? Is model = data tier, controller = business tier, view = presentation tier? I think I have misunderstood the whole concept.
You seem to have a decent understanding of MVC. The trouble is that you are looking at two different potential MVC structures as one and the same. On the server, you can have data models, controllers, and views. On the client side, you can ALSO have data models, controllers, and views. If you want to look at your client side JavaScript as MVC, then jQuery is simply a utility that the view controllers can use to manipulate the view (the DOM).
Simply put, the client side doesn't always have to be only the view. If you use a web application client-side framework like Backbone, for example, then you can have models, views, and controllers all on the client side, which communicate with another, SEPARATE MVC structure on your server.
What you describe does actually pose a challenge for a lot of implementations. Frameworks such as the ASP.NET MVC Framework have been making attempts to auto-render JavaScript to the UI based on business logic in the middle tier (validation rules for form fields, primarily). But they're a long way off from having a truly compelling JavaScript user experience which doesn't repeat logic.
Personally, I like to think of the JavaScript as purely a UI concern. The application internally handles all of the logic. The JavaScript, as part of the UI, may duplicate some of that logic... but only for strictly UI purposes. Remember that the application should regress gracefully into a still-working state if the user has JavaScript disabled. That is, it should still use server-side (middle-tier) code to get the job done. All the JavaScript did was add a richer user experience to the UI layer.
JavaScript isn't the only culprit for this, either. Suppose you have a lot of validation logic in your middle tier defining what's valid or invalid for your objects. When you persist those objects to a database (which is on the periphery of the application just like the UI is), doesn't that database also contain duplicate validation logic? Non-nullable fields and such.
Congratulations! Your understanding of MVC is completely wrong. It has nothing to do with n-tier architecture (which is what you seem to be confusing it with).
The core idea of MVC is separation of concerns. This is used by dividing the application it two major layers:
model layer: contains all of the domain business logic and rules.
presentation layer: deals it user interface
The presentation then is further split into controllers (for handling the user input) and views (for dealing with response).
When applied to web applications, you either have MVC (or MVC-like) structure only on server-side, or, for larger and more complicated applications, you have separate MVC triads for both frontend and backend.
Also, when working with applications, the user of MVC is not human being, but the browser.
In latter case the backend acts like one data source for frontend application. An the whole frontend part of MVC is written in javascript.
P.S. In case if you are able to read PHP code, you can find a quite simple explanation of model layer in this answer. And, yes. It is the "simple version" because MVC is a pattern for enforcing a structure in large application, not for making a guesbook.
You can go to http://www.asp.net/mvc site and refer tutorials / samples to learn about MVC using Microsoft technologies.

Razor-based MVC vs. Single Page Application in MVC 4

I used to utilize MVC 3 Razor engine to render pages. Sometimes I had to use AJAX calls to transfer Razor-rendered HTML and inserting it into the page using JQuery. As new project is starting, we do consider to utilize MVC 4 Single Page Application framework which is new to us. I took the first glance at it which left me with mixed feelings:
On the one hand it implies all your data are transferred by JSON and client does all the job to render them and encode some UI-related logic which is great for server and network performance. On the other hand the client (HTML+JavaScript) becomes much more heavy with a bunch of magic strings and hidden relations inside it which seems to be hard to maintain. We got used to VS intellisense, type-safed .NET server code to render pages which we have to exchange for client scripts and Knockout binding statements in case of SPA.
I wonder are any prons and cons of using SPA comparing to Razor, other that this obvious one I've mentioned here? Thanks
Razor is a server based technology where SPA (Single Page Application) is an architecture approach used on the client (web browser). Both can be used together.
From a high level, SPA moves the rendering and data retrieval to the client. The web server becomes a services tier sitting in front of the database. An MVC pattern works best when using SPA. Frameworks like Knockout.js and Backbone.js can be used for this. The net results is a rich responsive desktop like experience.
To achieve this you'll need to be a descent javascript programmer or be willing to learn javascript.
Yes it's moving business requirements from C# into javascript. In Visual Studio there is limited intelli-sense for javascript. To have confidence in your javascript you'll need to lean on unit testing. The up side is the rich user experience (think gmail or google maps).
I think it sounds like you are already fairly well apprised of most of the trade-offs here; you'll have reduced network load with SPA, and will shift a measure of the processing to the client. You will, however, increase the complexity of your code, and make it slightly harder to easily maintain the system (simply because of the increased complexity - not due to any architectural problems inherent in SPA).
Another thing to keep in mind is compatibility. The reason I mentioned a "false choice" in my comment to your question is that to keep the site usable for folks with Javascript disabled, you will still need to provide regular, whole-page views. This is also a good idea to do for the sake of SEO; a crawler will browse your site as a user with JS disabled, and can then index your site. The site should then handle such incoming URLs properly so that those with JS enabled will find themselves in your SPA looking at the same content (as opposed to being dumped in the "no JS" view unnecessarily).
There's something else I'll mention as a possibility that might help with the above, but it breaks the ideals of an SPA; that is, using Ajax-loaded partials in some places, rather than JSON data. For example, say you have a typical "Contact EMail" form on the site; you want that to load within the context of the SPA, but it's probably easier to do so by loading the partial via AJAX. (Though certainly, yes; you could do it with a JSON object describing the fields to display in the e-mail form).
There will also likely be content that is more "content" than "data", which you may still wish to load via partials and Ajax.
An SPA is definitely an interesting project, and I'm about to deploy one myself. I've used a mix of JSON and partials in it, but that may not be your own choice.

Need Help in Selection of Ajax Framework

My project's domain is of eTendering. And we are planing to use Spring and Hibernate in the architecture and in presentation Spring MVC but we want look and feel like silverlight of .Net or Flex of adobe in short we are planning for Ajax framework in presentaion. So SpringMVC will be worthfull? I have seen wicket and openxava but I am still confused so please suggest correct option in terms of my domain's complexity.
Depends on your needs:
Spring MVC - this option will leave you with writing AJAX on your own (via JQuery for instance) along with HTML and so forth. It might be tedious, but you're controlling everything. It's also up to you what will be the quality of your resulting HTML and how good it will be indexed by SEO.
JSF - this option provides you with a number of components and allows you to create AJAX based forms and handles it out-of-box. But when it comes to writing custom components, it won't that easy as just writing JS/JQuery on your own. Also it generates not that pretty HTML which is not of that good quality and you might be less indexed by SEOs.
GWT - this choice would mean that you don't write JS, instead you write logic in Java and then it transforms to JS. From one hand it will provide you with good-looking AJAX-based app where you don't need to write JS, from the other hand it's a) pretty complicated to write really good-looking apps UI b) it will add another step in your development cycle (it takes pretty much time when you generate that JS) c) it almost won't allow your pages to be indexed. Also, if it comes to such derivatives as SmartGWT, they provide a large set of cool-looking components, but they always require money for support.
Vaadin - this is AJAX based framework that partially generates Java to JS, but it also sends requests go server for logic execution (of course in GWT this happens as well, but not that often, GWT tries to execute logic on client). It takes less time to compile sources to JS and it's also almost impossible to make pages being indexed.
ZK - another AJAX based framework. unlike other frameworks that allow you to work with only one pattern, it can work in MVC, MVP, MVVM modes. It doesn't compile Java sources to JS thus all the requests go to the server (I've heard about internal company's benchmarks that showed it was actually faster than GWT, but I think it depends on your processing logic). SEO won't make it with ZK at all, but it's possible to include ZK components into JSP pages (though this functionality is not free) which makes it possible to kill both birds. It will be not trivial to write your own components with ZK, but it has a wide range of ready-to-use components.
So you should consider several things: SEO, money you can give for the framework, how much AJAX you need and do you want to write it on your own, etc.
Also pay attention to those patterns I mentioned: MVP for instance is suitable for complicated interfaces and is supported by GWT, Vaadin, ZK. MVVM is very cool because of its binding and is supported by JSF and ZK.

Is WordPress MVC compliant? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Closed 7 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Some people consider WordPress a blogging platform, some think of it as a CMS, some refer to WordPress as a development framework. Whichever it is, the question still remains. Is WordPress MVC compliant?
I've read the forums and somebody asked about MVC about three years ago. There were some positive answers, and some negative ones. While nobody knows exactly what MVC is and everybody thinks of it in their own way, there's still a general concept that's present in all the discussions.
I have little experience with MVC frameworks and there doesn't seem to be anything about the framework itself. Most of the MVC is done by the programmer, am I right? Now, going back to WordPress, could we consider the core rewrite engine (WP_Rewrite) the controller? Queries & plugin logic as the model? And themes as the view? Or am I getting it all wrong?
Thanks ;)
Wordpress itself is not architected in MVC, but one can build very MVC oriented themes and plugins within the framework. There are several tools which can help:
WordPress MVC solutions:
Churro: # wordpress.org/extend/plugins/churro
Tina-MVC: # wordpress.org/extend/plugins/tina-mvc
Plugin Factory: # wordpress.org/extend/plugins/plugin-factory
MVCPress: http://mozey.wordpress.com/2007/01/22/mvcpress-screenshots/#comment-3634 (abandoned, but interesting ideas)
MVC threads on WordPress.org Ideas and Trac:
http://wordpress.org/extend/ideas/topic/mvc-plugin-framework
http://wordpress.org/extend/ideas/topic/complete-reestructuring
http://wordpress.org/extend/ideas/topic/rewrite-wordpress-using-mvc
http://wordpress.org/extend/ideas/topic/wordpress-theme-revamp (more on XSL than MVC)
http://core.trac.wordpress.org/ticket/12354 (on MVC in widgets)
Wordpress is kinda-sorta MVC. If anything it is a pull-type MVC layout, where the View 'pulls' data from the model. It does this in a very proceedural way, instead of using lots of different objects, but this actually makes the front end templates easier to write in a lot of ways.
This also gives the views some degree of controller logic (thus the kinda-sorta MVC).
Lets run this down:
Wordpress gets a URL. The wordpress core acts as a controller and determines what initial queries to run of the database, and by extension, what view should be loaded (category view, single post or page view, etc). It then packages that INTIAL query response and sends it to the view file.
That view file CAN be a strict display only file OR it can request additional information/queries beyond the built in one. This is the pull-type of the MVC, where the view pulls data from the model instead of the controller 'pushing' data from the model into the view.
Thus, when the view sees code to load a sidebar or widget area, it asks for that information. However, what widgets should be there is determined by the controller, which looks at the model for what widgets are in the sidebar, and then selects those that are set to show on the current page, and returns those to the view.
That each part of that isn't an object doesn't make this any less MVC. You can alter WP core without (necessarily) altering anything about a theme. Similarly, as long as you use built in functions like 'get_pages()' then the model and the database tables could change as long as those functions still returned the right data. So, the model is independent of the view, and the controller is independent as well (except when the view adds controller logic to do more than the core normally does).
While you COULD have a model object holding a number of methods and stuff like WPModel::get_pages('blah blah'), and contain everything that way, there is still fundamental separation of concerns.
View: template files
Controller: WP core
Model: the various functions that handle specific data handling.
As long as the names, arguments, etc, stay the same (or just have new ones added) then separation of concerns is maintained and one can be altered without disturbing the others.
It isn't a super-clean version of MVC, (especially when hooks get involved), but at a basic level it starts there.
And being proceedural about it isn't a bad thing IMO. A request from a website is pretty inherently proceedural: it is a process with a clear beginning and end, and just needs a procedure to process the request, get data, package it, then die. You can set up those steps with objects and object methods and OOP layouts (which would make some things easier) or you can just write alot of function calls and separate them out that way. Class members like private variables are lost that way but depending on the needs of the application... you might not care.
There is no one-grand-way to do development, and WP sits at like 20% of websites so it is doing something right. Probably something to do with not making people have to learn/memorize complex class hierarchies to get the database to answer the question 'what pages are child of page x?' and deal with that data. Could you make it that easy with OOP? yes, but if Joomla is any example of how hard it is to implement a complex custom website with OOP, then WP is FAR easier and quicker, and time is money.
As already mentioned in the comments, MVC is an architectural design pattern, not a specific framework, and no, Wordpress doesn't follow the MVC pattern.
There is a separation of views (templates) from the programming logic, but only in the frontend, not in the admin panel and a general separation of views and application logic is not inevitably MVC. An implementation of the MVC pattern usually assumes some kind of object oriented programming paradigm behind it and Wordpress is mainly implemented in a procedural way, with plain SQL queries in the PHP functions, therefore not having an actual model either.
One of the topics that periodically crops up in discussions as it relates to WordPress is the idea of WordPress and MVC.
But the thing is that MVC is not the silver bullet of web development that we try to make it out to be. Yes, it’s an awesome design pattern, and I personally think that it fits the web application model like a glove, but not every framework or platform implements that design pattern.
Case in point: WordPress is not MVC.
And that’s okay. I think we need to leave the desire of trying to shoehorn it into our projects aside especially when the pattern WordPress provides is not only sufficient, but works well when leveraged correctly.
“But I Love MVC!”
So do I! In fact, I spent the last year working on a project that more-or-less mimicked the MVC architecture.
A high-level example of MVC.
A high-level example of MVC.
For example:
Views were implemented using templates
Controllers were implemented by a combination of using function names like create, read, update, destroy, delete, and so on (even though these functions were hooked into the WordPress API
Models were functions also were called to validate and verify data prior to serializing the data. Again, this required that certain functions be hooked into WordPress to achieve the desired result.
Finally, a set of rewrite rules gave the application a clean set of predictable URLs in the format of /people/update/1 or /people/all.
What Pattern Does WordPress Implement?
WordPress implements the event-driven architecture (of which there are several variations such as the Observer Pattern).
In short, you can conceptually think of this as the following:
Things happen when WordPress is processing information.
You can register your own function to fire when these things happen.
Not too complicated, is it?
A high-level example of event-driven patterns
A high-level example of event-driven patterns
When you begin to think in terms of the paradigm in which it works rather than trying to make it work the way that you want it to work, it’s liberating. It helps to solve problems much more easily.
The bottom line is this: WordPress implements the event-driven design pattern, so even if you end up trying to implement MVC, you’re still going to have to utilize the hook system.
If you’re not careful, you can end up trying to craft the perfect architecture without actually getting your work done, and thus end up finding yourself so high up in the atmosphere of software that you’ve effectively become an architecture astronaut.
So You’re Saying Avoid Design Patterns?
Not at all! Design Patterns serve a purpose because, above all else, they basically give us solutions to previously and commonly solved problems. Use them!
But the point I’m trying to make is that we don’t need to try to force things to fit pattern just because we like the pattern. That’s not their purpose. Instead, leverage the primary pattern that your platform of choice implements – in our case, it’s an event-driven pattern – and then implement patterns where they fit (such as dependency injection or something like that).
Otherwise, it’s like trying to put your foot in a glove.
Courtesy (and totally copied :P) from : http://tommcfarlin.com/wordpress-and-mvc/
Just to update this with more recent information for people hitting this from search engines - the wp-mvc plugin http://wordpress.org/extend/plugins/wp-mvc/ goes a long way to creating a mvc framework for plugin development. You can find out more here: http://wpmvc.org/documentation/70/tutorial/
Just to add to the list of options, (I'm admittedly biased as the author,) swpMVC is a fully featured, lightweight MVC framework, inspired by Rails, Sinatra, Express, and FuelPHP. It's thoroughly documented, and while I have used and enjoyed wp-mvc, I wanted something where the models were able to populate views themselves, including form controls for interacting with said models.
I put this together largely to reduce the amount of controller code required to put together an app on top of WordPress, and the result is a very fast and effective framework that runs inside WordPress. The models are based on PHP Activerecord and 8 models are included for existing WordPress data types, including Post, PostMeta, User, UserMeta, Term, and a few more. Modeling data is very easy thanks to the activerecord library, and I've enjoyed working with this framework immensely thus far.
Also ships with underscore PHP and PHP Quick Profiler (as seen in FuelPHP.)
RokkoMVC is a micro MVC framework built especially for WordPress. The project is meant to simplify AJAX functionality in WordPress applications, as well as bringing in all the other benefits of using models, views, and controllers to your theme.
I had a bash recently at creating a plugin that makes use of a simple view-controller system, and quite liked the results, so I separated the template stuff out to its own repo. It offers object-based controllers, passing variables locally to PHP templates, template fragments (templates within templates) and components (template fragments with their own sub-controller). All in two tiny classes!
Of course, I wrote this code thinking that no other WP developer had considered the problem before ;-).
It's far from mvc, there is no kinda-sorta thing like some people say, it's either MVC or not... The fact that you write logic on the view level doesn't qualify it as a mvc framework. The reason people use it - it's easy to learn, you don't need to be hardcore php programmer, they're lazy.

Which pattern would you choose for web application and why?

When you start a new web application, which pattern are you choosing between MVC and MVP and why?
(This answer is specific to web applications. For regular GUIs, see What are MVP and MVC and what is the difference?.)
Traditional MVC for GUI applications
This isn't really relevant to web applications, but here's how MVC traditionally worked in GUI applications:
The model contained the business objects.
The controller responded to UI interactions, and forwarded them to the model.
The view "subscribed" to the model, and updated itself whenever the model changed.
With this approach, you can have (1) multiple ways to update a given piece of data, and (2) multiple ways to view the same data. But you don't have to let every controller know about every view, or vice versa—everybody can just talk to the model.
MVC on the server
Rails, Django and other server-side frameworks all tend to use a particular version of MVC.
The model provides approximately 1 class per database table, and contains most of the business logic.
The view contains the actual HTML for the site, and as little code as possible. Basically, it's just templates.
The controller responds to HTTP requests, processes parameters, looks up model objects, and passes values to the view.
This seems to work very well for server-based web applications, and I've been very happy with it.
MVP on the client
However, if most of your code is written in JavaScript and runs in the web browser, you'll find lots of people using MVP these days. In this case, the roles are a bit different:
The model still contains all the basic entities of your business domain.
The view is a layer of fairly dumb widgets with little logic.
The presenter installs event handlers on the view widgets, it responds to events and it updates the model. In the other direction, the presenter listens for changes to the model, and when those changes occur, it updates the view widgets. So the presenter is a bidirectional pipeline between the model and the view, which never interact directly.
This model is popular because you can easily remove the view layer and write unit tests against the presenter and model. It's also much better suited to interactive applications where everything is updated constantly, as opposed to server applications where you deal with discrete requests and responses.
Here's some background reading:
Martin Fowler's encyclopedic summary of MVC, MVP and related approaches. There's a lot of good history here.
Martin Fowler's description of "Passive View", a variation of MVP.
Google's MVP + event bus
This is a new approach, described in this video from the Google AdWords team. It's designed to work well with caching, offline HTML 5 applications, and sophisticated client-side toolkits like GWT. It's based on the following observations:
Anything might need to happen asynchronously, so design everything to be asynchronous from the very beginning.
Testing browser-based views is much slower than testing models and presenters.
Your real model data lives on the server, but you may have a local cache or an offline HTML 5 database.
In this approach:
The view is very dumb, and you can replace it with mock objects when running unit tests.
The model objects are just simple containers for data, with no real logic. You may have multiple model objects representing the same entity.
The presenter listens to events from the view. Whenever it needs to update or read from the model, it sends an asynchronous message to the server (or to a local caching service). The server responds by sending events to the "event bus". These events contain copies of the model objects. The event bus passes these events back to the various presenters, which update the attached views.
So this architecture is inherently asynchronous, it's easy to test, and it doesn't require major changes if you want to write an HTML 5 offline application. I haven't used it yet, but it's next on my list of things to try. :-)
Both MVP and MVC make sense and allow to separate logic from display.
I would choose MVC because it's widely used in web development these days (Rails, .NET MVC which is used for SO) so my application will be more easily maintainable by someone else. It is also -to me- cleaner (less "power" given to the view), but this is subjective.
Another alternative is MTV, Model-Template-View which Django uses.

Resources