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

<?php e($this->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!