Using CakePHP Elements & RequestAction

Using CakePHP Elements & RequestAction

This problem arose while i was trying to get a random phrase from a database into the <title> HTML elements across all views. Being fairly new to CakePHP i was overwhelmed by some people’s solutions to accessing models site wide. However they forgot what CakePHP is based on, MVC. Breaking this system will leave you using CakePHP to how it shouldn’t be. So i decided to stick with the MVC method and found using Elements and RequestActions.

Elements are simply HTML blocks that can be included anywhere on a page. However the RequestActions that can be used with an element can link an Element to a View, and in turn access the Models brought in by the views controller. So i first created my Title model.

Models/title.php

class Title extends AppModel {

var $name = 'Title';

function getRandom(){
return $this->field('title',1,'rand()');
}

}

Then i designed the Element:
views/elements/random_title.ctp

$title = $this->requestAction('titles/random/');
echo ucwords($title);

And finally i included it in my layout file:
views/layouts/index.ctp

element('random_title', array('cache'=>'+5 minute')));?>

The important part here is the $this->requestAction(‘titles/random’); This requests that an action from a controller be executed and returned to the element. In my case it contacts the controller Titles and executes the Random Action/Function, which in turn contacts the model for the records that i need.

You will also notice that i have a cache here. It is set so i can simply recall this random phrase anywhere on my page, and not have to re-execute the code or use sessions. The CakePHP cache engine is amazing!

Posted by VoiDeT

Categorised under CakePHP
Bookmark the permalink or leave a trackback.

One Comment

  1. VoiDeT

    In fact this is not the best way to use it. It does in effect break the MVC design pattern, it works, however you should make sure you overdose on caching. It pretty much just makes 2 page requests, which isn’t the best idea. In effect i just called a model from my app_controller.php and passes the result into a $this->set and then used that variable in an element, easy! Also used cache ;)

    February 22, 2009 @ 1:16 pm

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

or