开发者

Why do so many MVC web frameworks favor grouping multiple controller actions in a single class?

My exper开发者_开发百科ience is mostly limited to PHP, yet as far as I know both Rails and ASP.NET MVC have taken the same path.

The point is that nearly every web framework I've ever come across implements controller actions as methods, e.g. create, edit, show, etc. These methods reside in a single class like PostsController, but they hardly ever share state or dependencies, because only one of them gets called during the whole request.

That's why to me this approach seems quite unreasonable, as the class only acts as some kind of namespace. Seeing examples with large chunks of barely related controller action code composing even larger controller classes doesn't help either. Yet a lot of frameworks do exactly that, and only a few use a class for each action.

So the question is, why is it so? Perhaps it's subjective, but I believe that I may have missed an important advantage of this approach.


I would argue that the MVC design pattern in general dictates this approach to building controllers. The main purpose of the controller is to provide the appropriate "wiring" between the associated view and the models it needs to interact with, along with any business logic needed to handle the input from the view. Controllers should just be a thin layer between these other components. For example, Wikipedia describes the controller as follows:

The controller receives input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and viewport to perform actions based on that input.

I do agree that controllers in other, non-web environments do maintain state, but the reason for the lack of state in PHP, for example, is simply that HTTP is a stateless protocol. Using MVC in this environment is inherently going to result in controllers that don't maintain state.


Why do so many MVC web frameworks favor grouping multiple controller actions in a single class?

That is essential to object oriented programming resulting in a properly layered software architecture where the controller objects encapsulate all responsibilities about domain objects (model). If there is a PostModel, then there should be a PostController responsible for calling the right business methods on the domain api to satisfy the user request and to push the results into the view. Having a controller class for every single possible request leads to a procedural structured architecture in my opinion.

On the other hand, if you have too many resonsibilities in your controller class, you should split these responsibilities into multiple controllers. It depends on your application at hand, there is no one-fits-all solution. Every controller should be responsible for a cohesive group of actions on the domain layer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜