我正在使用cakephp,并且开始习惯这些概念。我想知道使用MVC流做这件事的最好方法是什么。
假设这是我的默认值。ctp布局:
<body>
<div id="container"><?php echo $this->fetch('content'); ?></div>
<div id="tagcloud"></div>
</body>
我的控制器是Posts,当我调用index()动作时,它将列出数据库上的所有帖子。
我还有一个控制器标签,它访问一个表,每个标签被用来标记一个帖子的次数。
我需要的是生成一个标签云,应该在任何页面。那么,我应该在哪里写我的标签云代码?
我的第一个想法显然是写在标签控制器,但我将如何输出标签云的布局?
你可能想使用Components:
组件是控制器之间共享的逻辑包。如果你发现自己想要在控制器之间复制和粘贴东西,你可以考虑在组件中包装一些功能。
在这种情况下,您应该导入在组件中使用的模型。
在你的PostsController::index()中你可以这样做:
public function index() {
$this->set('posts', $this->paginate()); // pass a paginated list of posts to the view
$this->set('tagCloud', $this->Post->tag->tagcloud()); // pass the tag cloud data to the view
}
在你的标签模型中:
public function tagcloud() {
$tagcloud = //funky code to build a tagcloud
return $tagcloud;
}
或者,您可以将标记云打包到一个元素中:
/app/视图/元素/tagcloud.ctp:
<?php
$tagCloud = $this->requestAction('/tags/tagcloud');
// code to display your tag cloud in the Tag Model as before.
?>
并插入到索引中。
<?php echo $this->Element('tagcloud'); ?>
,在TagsController中:
public function tagcloud() {
return $this->tagcloud();
}
并将构建标记云的逻辑像以前一样放在标记模型中。