3.5.3 Controller Methods

For a complete list of controller methods and their descriptions visit the CakePHP API. Check out http://api.cakephp.org/1.2/class_controller.html.

3.5.3.1 Interacting with Views

3.5.3.1.1 set

set(string $var, mixed $value)

The set() method is the main way to send data from your controller to your view. Once you've used set(), the variable can be accessed in your view.

<?php
    
//First you pass data from the controller:

$this->set('color', 'pink');

//Then, in the view, you can utilize the data:
?>

You have selected <?php echo $color; ?> icing for the cake.
  1. <?php
  2. //First you pass data from the controller:
  3. $this->set('color', 'pink');
  4. //Then, in the view, you can utilize the data:
  5. ?>
  6.  
  7. You have selected <?php echo $color; ?> icing for the cake.

The set() method also takes an associative array as its first parameter. This can often be a quick way to assign a set of information to the view.

Array keys will be inflected before they are assigned to the view ('underscored_key' becomes 'underscoredKey', etc.):

<?php
    
$data = array(
    'color' => 'pink',
    'type' => 'sugar',
    'base_price' => 23.95
);

//make $color, $type, and $basePrice 
//available to the view:

$this->set($data);  

?>
  1. <?php
  2. $data = array(
  3. 'color' => 'pink',
  4. 'type' => 'sugar',
  5. 'base_price' => 23.95
  6. );
  7. //make $color, $type, and $basePrice
  8. //available to the view:
  9. $this->set($data);
  10. ?>

3.5.3.1.2 render

render(string $action, string $layout, string $file)

The render() method is automatically called at the end of each requested controller action. This method performs all the view logic (using the data you’ve given in using the set() method), places the view inside its layout and serves it back to the end user.

The default view file used by render is determined by convention. If the search() action of the RecipesController is requested, the view file in /app/views/recipes/search.ctp will be rendered.

class RecipesController extends AppController {
...
    function search() {
        // Render the view in /views/recipes/search.ctp
        $this->render();
    }
...
}
  1. class RecipesController extends AppController {
  2. ...
  3. function search() {
  4. // Render the view in /views/recipes/search.ctp
  5. $this->render();
  6. }
  7. ...
  8. }

Although CakePHP will automatically call it (unless you’ve set $this->autoRender to false) after every action’s logic, you can use it to specify an alternate view file by specifying an action name in the controller using $action.

If $action starts with '/' it is assumed to be a view or element file relative to the /app/views folder. This allows direct rendering of elements, very useful in ajax calls.

// Render the element in /views/elements/ajaxreturn.ctp
$this->render('/elements/ajaxreturn');
  1. // Render the element in /views/elements/ajaxreturn.ctp
  2. $this->render('/elements/ajaxreturn');

You can also specify an alternate view or element file using the third parameter, $file. When using $file, don't forget to utilize a few of CakePHP’s global constants (such as VIEWS).

The $layout parameter allows you to specify the layout the view is rendered in.

3.5.3.2 Flow Control

3.5.3.2.1 redirect

redirect(string $url, integer $status, boolean $exit)

The flow control method you’ll use most often is redirect(). This method takes its first parameter in the form of a CakePHP-relative URL. When a user has successfully placed an order, you might wish to redirect them to a receipt screen.

function placeOrder() {

    //Logic for finalizing order goes here

    if($success) {
        $this->redirect(array('controller' => 'orders', 'action' => 'thanks'));
    } else {
        $this->redirect(array('controller' => 'orders', 'action' => 'confirm'));
    }
}
  1. function placeOrder() {
  2. //Logic for finalizing order goes here
  3. if($success) {
  4. $this->redirect(array('controller' => 'orders', 'action' => 'thanks'));
  5. } else {
  6. $this->redirect(array('controller' => 'orders', 'action' => 'confirm'));
  7. }
  8. }

The second parameter of redirect() allows you to define an HTTP status code to accompany the redirect. You may want to use 301 (moved permanently) or 303 (see other), depending on the nature of the redirect.

The method will issue an exit() after the redirect unless you set the third parameter to false.

3.5.3.2.2 flash

flash(string $message, string $url, integer $pause)

Similarly, the flash() method is used to direct a user to a new page after an operation. The flash() method is different in that it shows a message before passing the user on to another URL.

The first parameter should hold the message to be displayed, and the second parameter is a CakePHP-relative URL. CakePHP will display the $message for $pause seconds before forwarding the user on.

For in-page flash messages, be sure to check out SessionComponent’s setFlash() method.

3.5.3.3 Callbacks

CakePHP controllers come fitted with callbacks you can use to insert logic just before or after controller actions are rendered.

beforeFilter()

This function is executed before every action in the controller. It's a handy place to check for an active session or inspect user permissions.

beforeRender()

Called after controller action logic, but before the view is rendered. This callback is not used often, but may be needed if you are calling render() manually before the end of a given action.

afterFilter()

Called after every controller action.

afterRender()

Called after an action has been rendered.

CakePHP also supports callbacks related to scaffolding.

_beforeScaffold($method)

$method name of method called example index, edit, etc.

_afterScaffoldSave($method)

$method name of method called either edit or update.

_afterScaffoldSaveError($method)

$method name of method called either edit or update.

_scaffoldError($method)

$method name of method called example index, edit, etc.

3.5.3.4 Other Useful Methods

3.5.3.4.1 constructClasses

This method loads the models required by the controller. This loading process is done by CakePHP normally, but this method is handy to have when accessing controllers from a different perspective. If you need CakePHP in a command-line script or some other outside use, constructClasses() may come in handy.

3.5.3.4.2 referer

Returns the referring URL for the current request.

3.5.3.4.3 disableCache

Used to tell the user’s browser not to cache the results of the current request. This is different than view caching, covered in a later chapter.

3.5.3.4.4 postConditions

postConditions(array $data, mixed $op, string $bool, boolean $exclusive)

Use this method to turn a set of POSTed model data (from HtmlHelper-compatible inputs) into a set of find conditions for a model. This function offers a quick shortcut on building search logic. For example, an administrative user may want to be able to search orders in order to know which items need to be shipped. You can use CakePHP’s Form- and HtmlHelpers to create a quick form based on the Order model. Then a controller action can use the data posted from that form to craft find conditions:

function index() {
    $o = $this->Orders->findAll($this->postConditions($this->data));
    $this->set('orders', $o);
}
  1. function index() {
  2. $o = $this->Orders->findAll($this->postConditions($this->data));
  3. $this->set('orders', $o);
  4. }

If $this->data[‘Order’][‘destination’] equals “Old Towne Bakery”, postConditions converts that condition to an array compatible for use in a Model->findAll() method. In this case, array(“Order.destination” => “Old Towne Bakery”).

If you want use a different SQL operator between terms, supply them using the second parameter.

/*
Contents of $this->data
array(
    'Order' => array(
        'num_items' => '4',
        'referrer' => 'Ye Olde'
    )
)
*/

//Let’s get orders that have at least 4 items and contain ‘Ye Olde’
$o = $this->Order->findAll($this->postConditions(
    $this->data,
    array('>=', 'LIKE')
));
  1. /*
  2. Contents of $this->data
  3. array(
  4. 'Order' => array(
  5. 'num_items' => '4',
  6. 'referrer' => 'Ye Olde'
  7. )
  8. )
  9. */
  10. //Let’s get orders that have at least 4 items and contain ‘Ye Olde’
  11. $o = $this->Order->findAll($this->postConditions(
  12. $this->data,
  13. array('>=', 'LIKE')
  14. ));

The key in specifying the operators is the order of the columns in the $this->data array. Since num_items is first, the >= operator applies to it.

The third parameter allows you to tell CakePHP what SQL boolean operator to use between the find conditions. String like ‘AND’, ‘OR’ and ‘XOR’ are all valid values.

Finally, if the last parameter is set to true, and the $op parameter is an array, fields not included in $op will not be included in the returned conditions.

3.5.3.4.5 paginate

This method is used for paginating results fetched by your models. You can specify page sizes, model find conditions and more. See the pagination section for more details on how to use paginate.

3.5.3.4.6 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.

You can use requestAction() to retrieve a fully rendered view by passing 'return' in the options: requestAction($url, array('return'));

If used without caching requestAction can lead to poor performance. It is rarely appropriate to use in a controller or model.

requestAction is best used in conjunction with (cached) elements – as a way to fetch data for an element before rendering. Let's use the example of putting a "latest comments" element in the layout. First we need to create a controller function that will return the data.

// controllers/comments_controller.php
class CommentsController extends AppController {
    function latest() {
        return $this->Comment->find('all', array('order' => 'Comment.created DESC', 'limit' => 10));
    }
}
  1. // controllers/comments_controller.php
  2. class CommentsController extends AppController {
  3. function latest() {
  4. return $this->Comment->find('all', array('order' => 'Comment.created DESC', 'limit' => 10));
  5. }
  6. }

If we now create a simple element to call that function:

// views/elements/latest_comments.ctp

$comments = $this->requestAction('/comments/latest');
foreach($comments as $comment) {
    echo $comment['Comment']['title'];
}
  1. // views/elements/latest_comments.ctp
  2. $comments = $this->requestAction('/comments/latest');
  3. foreach($comments as $comment) {
  4. echo $comment['Comment']['title'];
  5. }

We can then place that element anywhere at all to get the output using:

echo $this->element('latest_comments');
  1. echo $this->element('latest_comments');

Written in this way, whenever the element is rendered, a request will be made to the controller to get the data, the data will be processed, and returned. However in accordance with the warning above it's best to make use of element caching to prevent needless processing. By modifying the call to element to look like this:

echo $this->element('latest_comments', array('cache'=>'+1 hour'));
  1. echo $this->element('latest_comments', array('cache'=>'+1 hour'));

The requestAction call will not be made while the cached element view file exists and is valid.

In addition, requestAction now takes array based cake style urls:

echo $this->requestAction(array('controller' => 'articles', 'action' => 'featured'), array('return'));
  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 params in your url then the requestAction url array must wrap the named params in the key 'named'. This is because requestAction only merges the named args array into the Controller::params member array and does not place the named args in the key 'named'.

echo $this->requestAction('/articles/featured/limit:3');
  1. echo $this->requestAction('/articles/featured/limit:3');

This as an array in the requestAction would then be:

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

Unlike other places where array urls are analogous to string urls, requestAction treats them differently.

When using an array url in conjunction with requestAction() you must specify all parameters that you will need in the requested action. This includes parameters like $this->data and $this->params['form']