MVC: Are Models and Entity objects separate concep

2019-03-29 06:00发布

问题:

I asked here a while ago for some help in understanding MVC, since I'm very new to the topic. I thought I had a decent understanding of it, and this is documented in a blog post I wrote recently on the subject. My understanding basically boils down to this:

Controller: Determines what needs to be done to fulfill a request, and utilizes whatever models it needs to collect/modify as needed. It's basically a manager for a given process.

Views: Presentation only. Once a controller collects what it needs, it creates a specific type of view, hands it the information, and says "show this to the user however you do it."

Models: Behavior of the application. When the controller asks it to extract or modify something, it knows how to do it. It also knows to trigger other models to do related tasks (in my understanding, when a model tries to "vote for something" on StackOverflow, that model knows to ask if a badge should also be granted because of it. The controller doesn't need to care about that).

My question, assuming all of that is more or less accurate, is where do entity objects come in? Are models and entities the same thing, with each object knowing how to persist its own data, or are entities a separate concept that exist on their own and are used throughout the application?

My money is on the latter, since this would allow models to act independently, while all three layers (model, view and controller) could utilize the entities to pass data around as needed. Also, objects and database persistence seem like concerns that should be separated.

To be honest, the more I read about MVC the more confused I get. I'm about ready to just take the core concept (separate presentation from logic) and run with it in whatever way feels right, and not worry too much about the "MVC" label.

回答1:

Yes!

My money is on the latter, since this would allow models to act independently

You don't want to bind your view to an Entity, because if the view also needs some other piece of data, you would have to it to your Entity. The model is entirely supportive of the view, and is concerned with supporting that view and nothing else.

For example, you show a list of your entities, what other data might you need? Current page number? Total number of pages? A custom message to be displayed?

This is why you should bind to a model, which you can freely add data items to as you need to.

Update

Here is an explanation of MVC in action...

The controller gets all of the data required for the request and puts it into the model. It then passes the model to the view.

The view then deals with the layout of the data in the model.



回答2:

Each Model can be one entity that contains some methods to control and use its data.
Is it enough?