开发者

MVC: Should the view always receive arrays instead of objects?

I am wondering if the View should be pass开发者_如何学Goed 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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜