0
votes

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.

1

1 Answers

1
votes

You'll want to use requestAction():

You can take full advantage of elements by using requestAction(). The requestAction() function fetches view variables from a controller action and returns them as an array. This enables your elements to perform in true MVC style. Create a controller action that prepares the view variables for your elements, then call requestAction() inside the second parameter of element() to feed the element the view variables from your controller.

You can read more about them here: http://book.cakephp.org/2.0/en/views.html#passing-variables-into-an-element

Basically, you just specify where you want your element to retrieve it's data. When the element loads (regardless of on which page), it will run the specified action to retrieve whatever data you want it to have.