Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MVC, should the View know the Model?

Should the view know the model:

enter image description here

or not:

enter image description here

?

like image 353
The Student Avatar asked Oct 20 '22 19:10

The Student


1 Answers

Programmers often shortcut this and make the view specific to the model. For instance, if you're in a CRM app the model might have a firstName field; the view then assumes the model object it's given has a firstName field and shows that in the appropriate place.

This of course isn't reusable. If you are making a View to display a table of data, it shouldn't care which model field is shown in which column. It should just handle displaying and formatting tabular data in a generic way. But if your view is of a web page that's custom-built to the specific data it's showing, it can be okay.

So you have to decide on a case-by-case basis whether you want a view to know about the specific data it's showing or if you want it to be a reusable component.

In either way, any changes to the model's data should always happen through the controller. The controller is responsible for enforcing your business logic, and that's impossible when something else is circumventing it.

like image 63
Richard Connamacher Avatar answered Nov 01 '22 17:11

Richard Connamacher