-1

我用 cakephp 弄湿了我的脚,我开始习惯这些概念。我想知道使用 MVC 流程执行此操作的最佳方法是什么。

可以说这是我的 default.ctp 布局:

<body>
<div id="container"><?php echo $this->fetch('content'); ?></div>
<div id="tagcloud"></div>
</body>

我的控制器是 Posts,当我调用 index() 操作时,它将列出数据库中的所有帖子。

我还有一个控制器标签,它访问一个表格,每个标签用于标记帖子的次数。

我需要的是生成一个应该在任何页面中的标签云。那么,我应该在哪里编写我的 tagcloud 代码?

我的第一个任务显然是在标签控制器中编写它,但是我将如何将标签云输出到布局?

4

2 回答 2

1

您可能想要使用组件

组件是控制器之间共享的逻辑包。如果您发现自己想在控制器之间复制和粘贴内容,您可能会考虑在组件中包装一些功能。

在这种情况下,您应该导入要在组件中使用的模型。

于 2013-03-06T16:55:47.753 回答
1

在您的 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/View/Elements/tagcloud.ctp:

<?php

$tagCloud = $this->requestAction('/tags/tagcloud');

// code to display your tag cloud in the Tag Model as before.

?>

并插入您的 index.ctp 以获取帖子:

<?php echo $this->Element('tagcloud'); ?>

并在您的 TagsController 中:

public function tagcloud() {

   return $this->tagcloud();

}

并像以前一样将构建标签云的逻辑放在标签模型中。

于 2013-03-06T17:03:58.970 回答