开发者

MVC: Relationship between controller and model

开发者 https://www.devze.com 2023-01-11 01:14 出处:网络
I\'m slightly confused about 开发者_运维技巧the controller-model relationship in MVC. Should a controller be able to access any model in the system or should it have a 1:1 relationship with a specifi

I'm slightly confused about 开发者_运维技巧the controller-model relationship in MVC.

Should a controller be able to access any model in the system or should it have a 1:1 relationship with a specific model? Both options seem to present problems:

If the relationship is 1:1 obviously if something elsewhere needs to be updated it can't for example updating a window title from outside the window triad. So should models have access to other models (And how do they find them?)

If it's not 1:1 and the controller can access any model, how are these usually accessed (service locator?) and what if there needs to be more than one instance of a specific model.

I'm a bit confused! Thanks for any help.


For basic CRUD abilities I think a 1:1 relationship works, but it is by no means a rule that every controller should have a corresponding model. That being said, I obviously don't think it's an issue to access multiple models within a controllers.

The only thing that has a 1:1 relationship in my MVC applications is models and tables.


The MVC paradigm is based on one main rule, namely separation of concerns. Making a controller 1:1 dependent via some kind of relationship with a model is not separating those concerns, but making them more unified. A controller called "users" should only talk to a model called users, but why go and make that a explicit relationship?

Models should almost always exist in an exclusive static context, so they are easily accessed within controllers and other models.


Usually I don't access the model direct from the controller. I usually add another layer between the model and the controllers. For example: Controller Layer->Service Layer->Model Layer

For every Model class, I build a Service class to access it and the Controllers can access every Services in the application. I think it's a good way to do things. If you need some examples, please ask. :)

0

精彩评论

暂无评论...
验证码 换一张
取 消