控制器中的私有方法
大家好,
我现在已经开发了很多使用 MVC 模式的应用程序,无论是在 Rails 还是 .Net 中,我总是看到在控制器类中添加了一些私有方法。这些私有方法确实知道“如何”验证某些内容或“如何”创建域模型的视图模型。在我看来,这个逻辑正在泄漏,应该放置在助手内部或域模型本身中。我一直很喜欢这句话“控制器应该知道要做什么,但现在知道如何做”。似乎向类中添加一堆私有方法会破坏这一点。
我希望有人对此事有一些有用的见解。
谢谢!
Greetings,
I've worked on quite a few apps now that are using the MVC pattern be it in Rails or .Net and I always see a bit of private methods being added inside the controller class. These private methods are really knowing the "how" do validate something or the "how" to create a view model to a domain model. It seems to me that this logic is leaking and should be placed inside helpers or into the domain model itself. I always liked the phrase "A controller should know what to do, but now how to do it." and it seems adding a bunch of private methods to the class breaks this.
I'm hoping someone has some useful insight into the matter.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我同意这个逻辑不应该是控制器的一部分。我避免在控制器中使用私有方法。如果我们以“如何”创建域模型的视图模型为例,则此逻辑通常应驻留在映射层中。
I agree that this logic shouldn't be part of the controller. I avoid private methods in my controllers. If we take the example of "how" to create a view model to a domain model this logic normally should reside in the mapping layer.
我使用过 Spring MVC (3.0),并且喜欢它构建 servlet/web 服务的方式。
它具有:
每个 @RequestMappings(控制器中的公共方法)都充当 Web 服务。 HttpRequest 将进入,传递到正确的请求映射,映射到命令对象,然后进行验证。
像这样的事情:
需要注意的是,HTTP 请求的参数是使用反射映射到 GetUserCommand 对象的。因此必须有一个 FrontController 来解决这个问题,并确定将请求转发到哪个方法。
这里的关键是参数、验证、执行逻辑和视图选择被分成不同的组件。
您还可以使用 IoC 来构造命令对象及其所需的服务。我最终决定将 Command 对象拆分为Parameters 对象和Command 对象。参数对象包含用户 ID,而命令对象是使用参数(和 UserService)实例化的,并包含execute() 方法。它更冗长,但对我来说似乎是更好的分离。
I've used Spring MVC (3.0) and I liked how it structured servlets / web services.
It has:
Each of the @RequestMappings (public methods in the controller) acted as a web service. An HttpRequest would come in, be passed to the correct request mapping, mapped to the command object, then validated.
something like this:
It's important to note that the HTTP request's parameters are mapped to the GetUserCommand object using reflection. So there would have to be a FrontController which figures that out, as well as figuring out which method to forward the request to.
The key thing here is that the parameters, validation, execution logic, and choice of view are separated into different components.
You can also use IoC to construct the command object with the services it requires. I eventually decided to split the Command object into a Parameters object and Command object. The Parameters object contains the userid, while the Command object is instantiated with the Parameters (and UserService) and contains the execute() method. It was more verbose, but seemed like a better separation to me.