I'm building a blog using CakePHP (2.2.x) and one part of the blog is the sidebar. A sidebar like the wordpress one with recent posts, archives and meta. I'm not sure if I should use an element or a helper for the sidebar.
For the moment I'm using an element. Some code snippets:
Controller/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));
}
View/Posts/index.ctp
<div class="span8">
<?php foreach ($posts as $post) { ... } ?>
</div>
<?php echo $this->element('sidebar', array('posts' => $posts)); ?>
View/Posts/show.ctp
<div class="post">
... render the post using $post ...
</div>
<?php echo $this->element('sidebar', array('posts' => $posts)); ?>
View/Elements/sidebar.ctp
<?php foreach ($posts as $post) { ... render the recent posts ... } ?>
As you can see, both show.ctp
and index.ctp
include sidebar.ctp
element and both need $posts
variable. So I need to call $this->Post->find('all')
in both index
and show
actions.
I would like to call $this->Post->find('all')
just once and I wondering if using Helpers could, well, help.