MVC - Codeigniter - View talking to the model

752 Views Asked by At

In most of the posts I've seen on StackOverflow surrounding the MVC architecture, people have said that the model should only be communicated with from the controller, and not from the view.

I'm a little confused about this, because when you Google MVC: -http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller -http://i.msdn.microsoft.com/dynimg/IC108622.gif the graphics seem to indicate that there is communication from the view directly to the model.

The specific application I'm wondering about this for is an Ajax/jQuery hierarchical select box like the one here http://kotowicz.net/jquery-option-tree/demo/demo.html. After each selection I was thinking of getting the next box's data from the model. I'm using the Codeigniter framework.

Just after some expertise around the best practice here.

2

There are 2 best solutions below

0
On

When you have an XHR-centric application, it makes sense to actually have two triads of MVC. One for front-end and one for back-end. Front-end would treat the back-end MVC as just a source of data (same way as data abstraction structures in back-end's model layer treat database, cache and other forms of storage).

Basically, your "ajax application" is not view. It is should be a fully realized application. Of course, there is point in doing this if you are actually creating a large XHR-powered application.

Usually, what you see in the browser is NOT the view. It is just the response that view created. In context of the web, the user of MVC application is web-browser.


enter image description here source: wikipedia

The diagram above represents simplified flow of information in classical MVC and Model2 MVC (also known as "Web MVC"). The difference between them comes from nature of web: each time the user sends input, it expects to receive a response. This means that there is not ambiguity about timing. All the parts of MVC triad exists only till the response has been sent. There is no point for view to observe model layer.

View in you web application is actually the instance, which contains all the UI logic and is responsible for sending the response to the browser. The response, which it creates can be either a HTML (made by combining multiple templates), JSON or XML file. Or maybe just HTTP location header.

P.S. you might find this answer to be relevant for your studies.

0
On

I think the image on the second link is wrong 'cause the right way should be controller comunication with the model. If the view have directly comunication with the model means that html code is mixed with php arge sentences and that is a mistake.