MVC:视图应该始终接收数组而不是对象吗?
我想知道视图是否应该传递对象或者它们应该只接收数组。我正在使用 ORM 框架。因此,在项目视图页面中,我可以将视图传递给项目对象并让它渲染出项目的待办事项列表和待办事项吗?
所以目前在我看来我有这样的代码:
foreach ($this->project->getTodoLists() as $todoList) {
// render lists
foreach ($todoList->getTodos() as $todo) {
// render todos
}
}
这样可以吗?我认为通过原则的延迟加载,它会在调用 get*()
时运行 SQL。这里重要吗?
或者我应该在控制器中将所有必需的信息解析为纯数组?
我正在使用 PHP、Zend Framework 1.11、Doctrine 2 ORM。但我认为用什么并不重要
I am wondering if the View should be passed objects or should they only receive arrays. I am using an ORM Framework. So in the Project View Page, can I pass the view a project object and let it render out project's todoLists and todos.
So currently in my view I have code like:
foreach ($this->project->getTodoLists() as $todoList) {
// render lists
foreach ($todoList->getTodos() as $todo) {
// render todos
}
}
Is this ok? I think with doctrine's lazy loading, it runs SQL when get*()
is called. Does it matter here?
Or should I in my controller parse out every required info into pure arrays?
I am using PHP, Zend Framework 1.11, Doctrine 2 ORM. But it doesn't really matter what I use in my opinion
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用非惰性数据类型(即数组)进行视图渲染的优点之一是不会出现任何故障。例如,如果读取对象的值并触发调用最终失败的函数(数据库问题、内存不足等),则视图渲染可能会损坏(HTML 文档中的 IE 错误消息)。当您将数组传递给视图时,访问什么数据或以什么顺序访问并不重要,因为它是预渲染的。
虽然这个问题大部分可以通过输出缓冲来解决,但有些东西(例如致命错误)无法被捕获并且会泄漏到页面上。
当然,在像 PHP 这样的语言中,惰性可以帮助减少内存峰值(因为它是根据需要分配然后渲染的)和 CPU 使用率(如果您最终没有评估所有对象)。
最终,这取决于你希望你的观点有多复杂。简单的数据结构->简单视图,反之亦然。
One pro for using non-lazy datatypes (ie arrays) for view rending is that there is nothing to fail. For example if an object's value is read and triggers a function to be called that ends up failing (issue with db, out of memory, etc), the view rendering can corrupted (IE error messages in the HTML document). When you pass an array to the view, it doesn't matter what data is accessed or in what order since it's pre-rendered.
While this issue can be mostly overcome by output buffering, something (such as fatal errors) can't be caught and will leak onto the page.
Of course in a language like PHP, laziness can help reduce memory spikes (since it's alloc'ed as it's needed and then rendered) and CPU usage (if you don't end up evaluating all the objects).
In the end it comes down to how complex you want your views to be. Simple Data Structure -> Simple View, and via versa.