Wednesday, April 17, 2013

Introduction to MVC Concepts


The intension of MVC or Model-View-Controller is to build applications in a modular way. In MVC, 3 general parts/layers are responsible for creating the output and allowing the interaction with the user:

1.Model

2.View

3.Controller


Model:

In the context of the MVC the model has the data that is essential to render things in the view. So it represents the data that are mandatory for rendering. It also takes over the process related to the domain. The model is used to do something and get the data.

View:

A view takes care of “rendering the pixels on the screen“and should be as dump as possible. Naturally a view class understands one or more model(s) and outputs the information of that model. (A view is not allowed to write in the model.) So the view is conscious of the model and knows how to read the data out of it – but never the model should know something about the view!

Controller:

It glues together Model and View, it controls the user communication with the model and the view. (It’s a thin layer that connects models with their views)

The diagram below illustrates a common request cycle in an MVC application.


The process begins when a user takes an action on a web page – submitting a form that adds a new blog post, for example. The request is sent to the blog controller, which extracts the data submitted via the HTTP POST request and sends a message to the blog model to save a new post with this data.

The model checks the data against its validation rules. Assuming it passes validation; the model stores the data for this new post in the database and tells the controller it was successful. The controller then sets a variable for the view indicating success.

Finally, the view displays this message to the user back on the web page, and they know their new blog post has been successfully created. If, for some reason, validation of the data failed, the model would alert the controller of any errors, which would set a variable containing these errors for the view. The view would then present the original form along with the error messages for any fields that didn’t validate.


0 comments:

Post a Comment