【发布时间】:2013-01-12 18:39:01
【问题描述】:
我正在使用 CakePHP (2.2.x) 构建博客,博客的一部分是侧边栏。像 wordpress 这样的侧边栏,其中包含最近的帖子、档案和元数据。我不确定是否应该为侧边栏使用元素或助手。
目前我正在使用一个元素。部分代码sn-ps:
控制器/PostsController.php
public function index() {
$this->set('posts', $this->Post->find('all'));
}
public function show($id) {
$this->set('posts', $this->Post->find('all'));
$this->set('post', $this->Post->findById($id));
}
查看/帖子/index.ctp
<div class="span8">
<?php foreach ($posts as $post) { ... } ?>
</div>
<?php echo $this->element('sidebar', array('posts' => $posts)); ?>
查看/帖子/show.ctp
<div class="post">
... render the post using $post ...
</div>
<?php echo $this->element('sidebar', array('posts' => $posts)); ?>
视图/元素/sidebar.ctp
<?php foreach ($posts as $post) { ... render the recent posts ... } ?>
如您所见,show.ctp 和 index.ctp 都包含 sidebar.ctp 元素并且都需要 $posts 变量。所以我需要在index 和show 操作中调用$this->Post->find('all')。
我想打电话给$this->Post->find('all')一次,我想知道使用 Helpers 是否有帮助。
【问题讨论】: