简体   繁体   English

将数据从 Controller 发送到 View 或在 View 中有逻辑?

[英]Send data from Controller to View or have logic within View?

I have a webpage where I am trying to create a contextual menu depending on the category of the page being browsed.我有一个网页,我正在尝试根据所浏览页面的类别创建上下文菜单。 If the category is on animals , the segment based url will contain animal , ie.如果类别是animals ,则基于 url 的段将包含animal ,即。 http://www.mywebbie.com/livingthings/display/category/animals . http://www.mywebbie.com/livingthings/display/category/animals

To build the contextual menu, I will need to access my database table subcategory with columns subcat_id , subcat_name , cat_id and select all rows with cat_id corresponding to that of animals .要构建上下文菜单,我将需要访问我的数据库表subcategory ,其中包含subcat_idsubcat_namecat_idanimals列的所有cat_id对应于 animal 的行。

Should I access the database (via the model method) from the controller, then pass the array containing the subcategory names to the view?我是否应该从 controller 访问数据库(通过 model 方法),然后将包含子类别名称的数组传递给视图? Or should everything be done within the view, where there is code that loads the model method that returns an array of subcatergories?还是应该在视图中完成所有操作,其中有代码加载返回子类别数组的 model 方法?

Btw, I'm using PHP framework Codeigniter.顺便说一句,我正在使用 PHP 框架 Codeigniter。

Yes, The controller takes care of communicating with the model and handling the data, the view takes care of presenting the data.是的,controller 负责与 model 通信并处理数据,视图负责呈现数据。

Make the data available to the view from the controller, in the most simple form, lets say a simple array.从 controller 将数据提供给视图,以最简单的形式,让我们说一个简单的数组。

Not familliar with CI, but if you have some kind of ActiveRecord or ORM, then add a getAllSubCats() method to the category(?) entity and call it when you loop through categories.不熟悉 CI,但是如果你有某种 ActiveRecord 或 ORM,那么在 category(?) 实体中添加一个 getAllSubCats() 方法,并在循环分类时调用它。

If the above doesn't make sense: View shouldn't even know a database exists, so to answer your question, do it in the Controller.如果以上没有意义: View 甚至不应该知道数据库存在,所以要回答您的问题,请在 Controller 中进行。 Or better yet, do the fetching in the Model and pass the results back into the Controller.或者更好的是,在 Model 中进行提取并将结果传递回 Controller。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM