MVC 中的递归函数应该放在哪里?
我有一个递归函数用于在我的网站上生成菜单。该函数为菜单中的每个级别的子级调用数据库,并为它们生成 html。
我目前已将此函数放在代码的模型部分中,但是,我觉得在模型中生成 html 违背了 MVC。 我没有将其放入控制器中,因为我不想在那里进行数据库调用或 HTML 生成。 我没有将其放在视图中,因为我也不希望在那里进行数据库调用。
解决此问题的“正确”方法是让控制器调用模型中的递归函数,该函数返回表示菜单的二维数组。然后将数组传递给一个视图,该视图有自己的递归函数,用于从数组生成 html?
I have a recursive function being used to generate a menu on my site. The function is calling a database for each level of children in the menu, and generating html for them.
I've currently put this function in a Model part of the code, however, I feel that generating html in the model goes against the MVC.
I didn't put it in a Controller because I didn't want to have database calls or HTML generation there.
I didn't put it in a View because I didn't want database calls there either.
Is the 'correct' way of tackling this problem to have a Controller call a recursive function in a Model that returns a 2d array representing the menu. Then pass the array to a view which has it's own recursive function for generating html from the array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如您所建议的,最好的方法可能是让模型获取所有数据。然后以适当的格式将其提供给视图。然后在视图中递归生成html。
As you suggest the best way would probably be to have the model fetch all the data. And then supply that to the view in a appropriate format. Then generate the html recursively in the view.
您必须从模型返回完整的菜单数组/嵌套数组。
You must return from model complete menu array/nested arrays.
我在我的项目中创建了一个组件,它从数据库,格式化包含菜单项的数组并缓存它。然后我创建了一个 helper 来获取该数组并创建一个包含可在视图和布局中使用的菜单项的 html 列表。
因此,在布局中我有:
echo $databaseMenus->makeMenu($mainMenu);
其中makeMenu
是助手的方法,$mainMenu
是组件提供的数组。I created a component in my project that retrieves the menu data from the database, formats the array containing menu items and caches it. Then I created a helper that takes that array and creates an html list with menu items which can be used in views and layouts.
So, in the layout I have:
echo $databaseMenus->makeMenu($mainMenu);
wheremakeMenu
is the helper's method and$mainMenu
is the array provided by the component.