开发者

In MVC, how do you structure #Controllers with respect to Views, Models and Routing?

I have a question concerning the structure of an MVC application. Suppose we have to realize a web-based application composed by several modules, such as shopping cart, store browser(end-user), store manager(admin) and so on.

It is of course possible to create one controller and use the routing to submit the requests to a specific controller's action method. However thi开发者_StackOverflow社区s would make the code quite messy and hinder the practice to vertically structure the application, namely to identify and distinguish which views, models and controllers are involved to fulfill a specific requirement (an example is given by Phil Haack).

Another approach is to use one controller for each application section, for instance one controller made available for end-user operations, another for the store administrator, another one for queries made by the shipping department and so on. The drawback to this approach is to have too many controllers that mess up your code, too dedicated for specific tasks and so difficult to reuse.

According to this two extreme situation, what is the best way to organize your controllers and routing policies? Do you use a structured approach or it depends on the type of application you are developing?

Thanks

Francesco


It is of course possible to create one controller and use the routing to submit the requests to a specific controller's action method. [...]

Another approach is to use one controller for each application section, [...]

You're overlooking a third alternative, which is the most common one. In general you should have one controller per resource. A resource is a model that is publicly exposed. In your specific storefront application, the resources would be things like Products, Orders, Customers, etc.

This is typically the proper level of abstraction, because controllers usually don't need to know about models other than the resources they touch. A controller that touches more than one resource should be viewed with some skepticism, since it's violating the single-responsibility principle.


You should try to follow REST as much as possible

Basically - that means controller for each 'collection' (Your entity).

If Your controllers will be RESTful, other parts (routing, views) will fit themselves accordingly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜