Thursday, December 1, 2011

RequestAction in CakePhp

RequestAction
 
 
   
I am in a situation where i need to fetch data from 6 models. i can't use associations as they are not related. So what should i use $uses or request action or any other solution



Syntax of requestAction

requestAction(string $url, array $options)

This function calls a controller's action from any location and returns data from the action. The $url passed is a CakePHP-relative URL (/controllername/actionname/params). To pass extra data to the receiving controller action add to the $options array.


Example


  1. echo $this->requestAction(array('controller' => 'articles', 'action' => 'featured'), array('return'));

This allows the requestAction call to bypass the usage of Router::url which can increase performance. The url based arrays are the same as the ones that HtmlHelper::link uses with one difference - if you are using named or passed parameters, you must put them in a second array and wrap them with the correct key. This is because requestAction merges the named args array (requestAction's 2nd parameter) with the Controller::params member array and does not explicitly place the named args array into the key 'named'; Additional members in the $option array will also be made available in the requested action's Controller::params array.


Suppose there is a function in class


class CommentsController extends AppController {
function latest() {
$comments = $this->Comment->find('all', array('order' => 'Comment.created DESC', 'limit' => 10));
if (!empty($this->params['requested'])) {
return $comments;
} else {
$this->set(compact('comments'));
}
}

}



And there is we r using the requestAction




$comments = $this->requestAction('/comments/latest');
foreach($comments as $comment) {
echo $comment['Comment']['title'];
}