最佳实践 - 从视图访问域对象列表?
只是想知道(在 Grails/Java 中)在 MVC 设计的视图/gsp 中调用: Foo.list()
是否是不好的做法,而不是通过模型传递它(即 foos: Foo.list()
) 并使用它?
在我看来,由于显示如此简单,所以这很好,但另一方面我知道直接从视图访问域对象是不好的做法。
提前致谢。
Just wondering if (in Grails/Java) it was bad practice to call: Foo.list()
in the view/gsp of a MVC design, rather than passing it through the model (ie foos: Foo.list()
) and using that?
Seems to me that since it is so simple of a display, that this is fine, but on the other hand I know that it is bad practice to access the domain object directly from the view.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您所做的事情通常被认为是一种不好的做法。原因很简单:你的视图与你的模型紧密相连。让我们看看结果:
Foo
实例列表。因此,您需要有一个max
参数,并且它将像Foo.list(max: params.max)
在您的视图内一样使用。max
是您可以想象的数百个参数中的一个(顺序、排序...)。因此,您的视图不仅取决于域实例,还取决于请求参数,您必须处理它们。结论:您可以为原型设计或不会重用的视图(例如管理内容)执行此操作。其他情况就别想了。
What you are doing is generally considered as a bad practice. The reason is very simple: your view is tightly linked with your model. Let's discover the consequences :
Foo
instances with pagination enabled. You need therefore to have amax
parameter and it will be used likeFoo.list(max: params.max)
inside your view.max
is a parameter out of hundreds that you can imagine (order, sort...). So, your view is not only dependent on the Domain Instance but it also depends on the request params and you have to process them.Conclusion: You can do this for prototyping or for views that will not be reused (like admin stuff for instance). Forget it for other situations.
不这样做的一个非常实际的原因是您最终可能希望在不同的操作中使用相同的视图,最终以某种方式过滤数据。您可能并不总是想处理 Domain.list()。
A very practical reason not to do that is you may end up wanting to use the same view from different actions where you end up filtering the data in some way. You might not always want to process Domain.list().
我认为在原型阶段,这样的陈述“在某种程度上”是可以接受的。
但是,更现实的是,这么简单的事情在生产代码中并不会发生太多。当您开始操作数据,或者说,检索许多不同的对象并用它们做一些事情时,您会发现您可能想要返回完全不同的东西到 UI 层...
现在,如果您已经开始构建一些 flash 的东西早期发表的一项声明,这将导致您必须重新编写部分 UI 代码...这不太好,并且可能会导致头痛。
另外,您已经回答了自己的问题:是的,我认为这是不好的做法。
I would argue that during the prototype phase statements like this are "somewhat" acceptable.
But, more realistically, stuff this simple doesn't really happen much in production code. When you start manipulating data, or say, retrieving a lot of different objects and doing something with them you will find that you might want to return something entirely different to the UI layer...
Now, if you have started building something flash out of that one statement made early on, this will cause you to have to rework parts of the UI code... this is not so good, and can potentially cause headaches.
Also, you've answered you own question: yeah, I would consider it bad practice.
我同意这是不好的做法。即使是在原型设计期间,从控制器传递它也不会增加很多额外的时间。
I agree this is bad practice. Even if it is during prototyping, passing it from the controller is not like it is going to add a lot of extra time.