0

我的控制器返回一个多行多列的 PDO 数组。循环浏览我的视图文件中的数据的最佳方法是什么?(或者我应该在模型中做更多的逻辑?)

$user->getDetails();  //returns array in view


foreach($user->getDetails() as $row)  // Prehaps? But how to index without being explicit with column names?

谢谢!

4

4 回答 4

2

视图的重点是运行与视图相关的逻辑和输出结果(即获取数据并根据需要对其进行格式化……如果是 JSON 视图,则输出 JSON。HTML 输出 HTML 等),因此您正在做对的。无论您认为合适,都可以循环遍历它,但是如果没有有关您的数据结构的更多详细信息,我们不能说比您已经想出的更多。

于 2012-07-31T14:55:59.940 回答
1
    foreach( $user->getDetails() as $row ){
       echo $row->name;
       echo $row->id;
    }

您不需要将 $user->getDetails() 放在顶部,它会调用 foreach 中的函数。

于 2012-07-31T14:58:23.553 回答
1

最好的方法或正在使用的方法MVC是将您的编程逻辑保留在控制器中,在模型中做数据库相关的东西并在视图中格式化布局。在您的情况下,您应该$user->getDetails();在控制器中调用,然后在视图中传递结果,然后循环它以输出数据,即

在控制器中,您可以使用$user->getDetails()

$user_details=$user->getDetails();

然后$user_details在加载它并在视图循环中传递给视图

foreach( $user_details as $row ){
   echo $row->id;
   echo $row->name;
}

如果结果是一个array of arrays而不是an array of objects那么你可以使用如下

foreach( $user_details as $row ){
   echo $row['d'];
   echo $row['name'];
}

更新 :

  1. 模型负责管理数据;它存储和检索应用程序使用的实体,通常来自数据库,并包含应用程序实现的逻辑。
  2. 视图(表示)负责以特定格式显示模型提供的数据。它与一些流行的 Web 应用程序中的模板模块有类似的用法,例如 wordpress、joomla ......</li>
  3. 控制器处理模型层和视图层以协同工作。控制器接收来自客户端的请求,调用模型执行请求的操作并将数据发送到视图。视图格式化要呈现给用户的数据,在 Web 应用程序中作为 html 输出。

参考: PHP和This中的模型视图控制器(MVC)

于 2012-07-31T15:26:01.230 回答
1

模型层应该包含所有的业务逻辑。它不应该向控制器返回任何东西。相反,控制器应该只向模型层结构发送消息。

The data from model layer should be extracted by view instance. And depending on nature of data, it would decide which templates to apply.

Views in MVC are supposed to contain all the presentation logic and ( in case of web-related MVC-inspired design patterns) deal with multiple templates. You should also be aware that there exists a 1:1 relation between views and controllers.

If if part of information, that view receives from model layer, is some sort of array, you have two choices. Either you take a template, which can render a single item and repeatedly generate the HTML/JSON/text/XML fragment or you use a template , which expect to receive an array as variable and already contains a loop. The latter approach is usually the more pragmatic one, but each of them as a specific cons an pros.

于 2012-07-31T16:50:06.083 回答