Welcome to the Cookbook

loading...

3.5.5 Controller Methoden

Der Originaltext dieses Abschnitts hat sich seit der letzen Übersetzung geändert. Bitte hilf dabei die Unterschiede zu lösen. Du kannst:

Mehr Informationen zu Übersetzungen

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.5.1 Interagieren mit Views

3.5.5.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.5.1.2 render

Der Originaltext dieses Abschnitts hat sich seit der letzen Übersetzung geändert. Bitte hilf dabei die Unterschiede zu lösen. Du kannst:

Mehr Informationen zu Übersetzungen

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.5.2 Flow Control

3.5.5.2.1 redirect

Der Originaltext dieses Abschnitts hat sich seit der letzen Übersetzung geändert. Bitte hilf dabei die Unterschiede zu lösen. Du kannst:

Mehr Informationen zu Übersetzungen

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

Die flow control-Methode, die am häufigsten benutzt wird, ist redirect(). Ihren ersten Parameter erhält die Methode in Form einer URL relativ zu CakePHP. Wenn ein Nutzer eine Bestellung erfolgreich aufgegeben hat, soll meistens an eine Bestätigungsseite umgeleitet werden.

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

Man kann auch relative oder absolute URL als $url-Argument angeben:

$this->redirect('/orders/thanks'));
$this->redirect('http://www.example.com');
  1. $this->redirect('/orders/thanks'));
  2. $this->redirect('http://www.example.com');

Man kann ebenfalls Daten an die action übermitteln:

$this->redirect(array('action' => 'edit', $id));
  1. $this->redirect(array('action' => 'edit', $id));

Der zweite Parameter der redirect()-Methode erlaubt die Definition eines HTTP-Status Code, der mit dem redirect übermittelt wird. Je nach Grund des redirect könnte man zum Beispiel 301 (permanent verschoben) oder 303 (siehe weitere) angeben.

Die Methode gibt nach der Weiterleitung einen exit()-Code aus, falls der dritte Paramater nicht auf false gesetzt wurde.

Zur Weiterleitung auf die Referer-Seite kann man folgendes benutzen:

$this->redirect($this->referer());
  1. $this->redirect($this->referer());

3.5.5.2.2 flash

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

Genauso wie die redirect()-Methode, wird die flash()-Methode verwendet, um Nutzer nach einer Operation auf eine neue Seite zu umzuleiten. Die flash()-Methode unterscheidet sich in der Hinsicht, dass bereits vor der Weiterleitung auf die andere URL eine Meldung angezeigt wird.

Der erste Parameter sollte die Meldung sein, die ausgegeben wird und der zweite Parameter die URL relativ zu CakePHP. CakePHP zeigt $message für die Dauer von $pause Sekunden, bevor der Nutzer weitergeleitet wird.

Für in-page flash-Meldungen, schaue Dir auch die SessionComponent’s setFlash()-Methode an.

3.5.5.3 Callbacks

Es gibt zur Zeit keine Übersetzung für diesen Abschnitt. Bitte hilf mit und übersetze ihn. Mehr Informationen zu Übersetzungen

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, and after rendering is complete. This is the last controller method to run.

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.5.4 Other Useful Methods

3.5.5.4.1 constructClasses

Es gibt zur Zeit keine Übersetzung für diesen Abschnitt. Bitte hilf mit und übersetze ihn. Mehr Informationen zu Übersetzungen

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.5.4.2 referer

Der Originaltext dieses Abschnitts hat sich seit der letzen Übersetzung geändert. Bitte hilf dabei die Unterschiede zu lösen. Du kannst:

Mehr Informationen zu Übersetzungen

Liefert die Verweis-URL für die aktuelle Anfrage.

3.5.5.4.3 disableCache

Wird verwendet, um dem Browser des Nutzers mitzuteilen, dass des Ergebnis des aktuellen Requests nicht gecached werden soll. Dies ist ein Unterschied zum view caching, das in einem späteren Kapitel behandelt wird.

Folgende Header werden zu diesem Zweck gesendet:

  • Expires: Mon, 26 Jul 1997 05:00:00 GMT
  • Last-Modified: [current datetime] GMT
  • Cache-Control: no-store, no-cache, must-revalidate
  • Cache-Control: post-check=0, pre-check=0
  • Pragma: no-cache

3.5.5.4.4 postConditions

Es gibt zur Zeit keine Übersetzung für diesen Abschnitt. Bitte hilf mit und übersetze ihn. Mehr Informationen zu Übersetzungen

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() {
    $conditions=$this->postConditions($this->data);
    $orders = $this->Order->find("all",compact('conditions'));
    $this->set('orders', $orders);
}
  1. function index() {
  2. $conditions=$this->postConditions($this->data);
  3. $orders = $this->Order->find("all",compact('conditions'));
  4. $this->set('orders', $orders);
  5. }

If $this->data[‘Order’][‘destination’] equals “Old Towne Bakery”, postConditions converts that condition to an array compatible for use in a Model->find() 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’
$condtions=$this->postConditions(
    $this->data,
    array(
        'num_items' => '>=', 
        'referrer' => 'LIKE'
    )
);
$orders = $this->Order->find("all",compact('conditions'));
  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. $condtions=$this->postConditions(
  12. $this->data,
  13. array(
  14. 'num_items' => '>=',
  15. 'referrer' => 'LIKE'
  16. )
  17. );
  18. $orders = $this->Order->find("all",compact('conditions'));

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.5.4.5 paginate

Es gibt zur Zeit keine Übersetzung für diesen Abschnitt. Bitte hilf mit und übersetze ihn. Mehr Informationen zu Übersetzungen

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.5.4.6 requestAction

Es gibt zur Zeit keine Übersetzung für diesen Abschnitt. Bitte hilf mit und übersetze ihn. Mehr Informationen zu Übersetzungen

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 or passed parameters, you must put them in a second array and wrap them with the correct key. 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');
echo $this->requestAction('/articles/view/5');
  1. echo $this->requestAction('/articles/featured/limit:3');
  2. echo $this->requestAction('/articles/view/5');

As an array in the requestAction would then be:

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

echo $this->requestAction(array('controller' => 'articles', 'action' => 'view'), array('pass' => array(5)));

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

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']. In addition to passing all required parameters, named and pass parameters must be done in the second array as seen above.

3.5.5.4.7 loadModel

loadModel(string $modelClass, mixed $id)

Die loadModel-Funktion ist dann sehr praktisch, wenn man ein Model benötigt, welches nicht Standard-Model des Controllers oder ein assoziiertes Model ist.

$this->loadModel('Article');
$recentArticles = $this->Article->find('all', array('limit' => 5, 'order' => 'Article.created DESC'));
  1. $this->loadModel('Article');
  2. $recentArticles = $this->Article->find('all', array('limit' => 5, 'order' => 'Article.created DESC'));
$this->loadModel('User', 2);
$user = $this->User->read();
  1. $this->loadModel('User', 2);
  2. $user = $this->User->read();