in MVC, where do you draw the line between a contr

2019-01-07 09:41发布

问题:

I've seen code written where almost all non-route related code is passed to a model. I have also seen code where all database persistence is handled by a model, but non-DB processing is handled by the controller.

Which is the better approach?

回答1:

The line between controller and model is actually quite clear.

Model is your application's heart. It contains the business/domain logic required to solve the problem your application was written for. The Model is usually layered into several other layers, e.g. persistence, services, domain, etc. It's a common misconception that the Model is just the database, as much as it is a common misconception that the database should be an ActiveRecord.

The controller (and the view) are part of the presentation layer. A controller's sole responsibility is to receive and handle user input directed towards your application and delegate this to the appropriate parts in the model. Nothing more. It should not handle complex application flow or code of your problem domain. You want controllers to be skinny and models fat with logic. The Model should not know about either C or V and you should be able to swap out V and C for a different presentation layer without having to touch your M.

See MVC Excerpt in Patterns of Enterprise Application Architecture