3.5.3 Controller Methoden

Eine vollständige Liste aller Controller-Methoden und deren Beschreibung gibts in der CakePHP-Api. Gehe zu 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)

Die set()-Methode ist die hauptsächliche Möglichkeit um Daten vom Controller an den View zu senden. Nachdem set() verwendet wurde, kann die Variable im View verwendet werden.

<?php
    
//Als erstes schickst du die Variable im Controller los:

$this->set('farbe', 'rosa');

//Dann kann die Variable im View benutzt werden:
?>

Du hast <?php echo $farbe; ?> Zuckerstreusel für den Kuchen gewählt.
  1. <?php
  2. //Als erstes schickst du die Variable im Controller los:
  3. $this->set('farbe', 'rosa');
  4. //Dann kann die Variable im View benutzt werden:
  5. ?>
  6.  
  7. Du hast <?php echo $farbe; ?> Zuckerstreusel für den Kuchen gewählt.

Die set()-Methode ist auch in der Lage mit nur einem Parameter, der ein assoziativer Array sein muss, aufgerufen zu werden um mit einem Aufruf von set() eine ganze Menge an Variablen an den View zu schicken.

Die Schlüssel aus einem Array werden dabei flektiert. (z.B. 'schluessel_mit_unterstrich' wird zu 'schluesselMitUnterstrich').

<?php
    
$data = array(
    'farbe' => 'rosa',
    'typ' => 'zucker',
    'preis_brutto' => 23.95
);

//stellt dem View$farbe, $typ
//und $preisBrutto zur 
$this->set($data);  

?>
  1. <?php
  2. $data = array(
  3. 'farbe' => 'rosa',
  4. 'typ' => 'zucker',
  5. 'preis_brutto' => 23.95
  6. );
  7. //stellt dem View$farbe, $typ
  8. //und $preisBrutto zur
  9. $this->set($data);
  10. ?>

3.5.3.1.2 render

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

Die render()-Methode wird normalerweise sowieso automatisch nach jeder aufgerufenen Aktion gestartet. Mit dieser Methode kann man den View in Gang setzen, der die Variablen, die man per set() zur Verfügung gestellt hat, für den Benutzer aufbereitet. Danach wird der View an die entsprechende Stelle im Layout gesetzt (dort wo man $content_for_layout ausgeben lässt) und schließlich an den Browser geschickt.

Den Namen der Standard-View-Datei, die render() nutzt wird per Namenskonvention ermittelt. In der suche()-Aktion des RezepteControllers wird die datei /app/views/rezepte/suche.ctp benutzt.

Zwar ruft CakePHP die Funktion sowieso nach Ausführung einer Aktion auf (solange $this->autoRender true ist), allerdings kann man mit dieser Methode auch einen alternativen View rendern lassen (zum Beispiel könnte eine Bildergalerie in einer einzigen Aktion sowohl die Vorschaubilder als auch (wenn ein Bildname gegeben ist) das Bild selbst darstellen und dafür unterschiedliche Views benutzen). Das geht am einfachsten indem man als ersten Parameter einfach den Namen der Aktion gibt, für die der View gerendert werden soll (womit dann wieder die Standard-View-Datei der gegebenen Aktion gerendert wird). Die Aktion muss dabei im Controller selbst nicht existieren. Man kann im dritten Parameter auch direkt eine Datei angeben. In dem Fall ist darauf hinzuweisen, dass es nützliche Globale Konstanten gibt (z.B. VIEWS) die beim spezifizieren der Datei hilfreich sind.

Mit dem zweiten Parameter kann man ein alternatives Layout bestimmen, in dem der View gerendert werden soll (nicht vergessen: das Layout muss dann irgendwo $content_for_layout ausgeben lassen, sonst wird der View nicht angezeigt).

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']