3.5.3 Metodi del Controller
Per una lista completa dei metodi del controller e la loro descrizione vista le CakePHP API. Visita 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)
Il metodo set() è il mezzo principale per inviare dati dal controller alla vista. Una volta usata set(), la variabile potrà essere utilizzata nella vista.
<?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.
<?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.
Il metodo set() utilizza un array associato come primo parametro. Questa può essere spesso utlizzata come modo veloce per assegnare delle informazioni alla vista. Notare che le chiavi dell'array verranno prima flesse prima di essere assegnate alla vista ('underscored_key' diventa '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);
?>
<?php$data = array('color' => 'pink','type' => 'sugar','base_price' => 23.95);//make $color, $type, and $basePrice//available to the view:$this->set($data);?>
3.5.3.1.2 render
render(string $action, string $layout, string $file)
Il metodo render() è chiamato automaticamente alla fine di ogni azione richiesta al controller. Questo metodo esegue tutte le logiche della vista (usando i dati utilizzati nel metodo set()), inserisce le viste nel proprio layout e le restituisce all'utente finale.
La vista di default usata dal render è determinata dalla convenzione. Se l'azione search() del RecipeController viene richiesta, la vista /app/views/recipes/search.ctp sarà restituita.
Sebbene CakePHP automaticamente la chiamerà (a meno che non si è settato $this->autoRender a false) dopo ogni azione logica, è possibile specificare una vista alternativa, specificando un nome di azione nel controller utilizzando $action. E' possibile inoltre un file alternativo di vista usando il terzo parametro, $file. Usando $file, non dimenticare di utilizzare poche costanti globali di CakePHP (come VIEWS).
Il parametro $layout permette di specificare il layout utilizzato dalla vista.
3.5.3.2 Controllo di Flusso
3.5.3.2.1 redirect
redirect(string $url, integer $status, boolean $exit)
Il metodi di controllo del flusso usato più spesso è redirect(). Questo metodo prende il primo parametro nella form di un indirizzo CakePHP-URL. Quando un utente ha ordinato correttamente qualcosa, vorresti ridirezionarlo ad una schermata di ricevuta d'ordine.
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'));
}
}
function placeOrder() {//Logic for finalizing order goes hereif($success) {$this->redirect(array('controller' => 'orders', 'action' => 'thanks'));} else {$this->redirect(array('controller' => 'orders', 'action' => 'confirm'));}}
Il secondo parametro di redirect() permette di definire uno stato HTTP per accompagnare il redirect. Potresti utilizzare 301 (moved permanently) o 303 (see other), a seconda della natura del redirect.
Il metodo userà un exit() dopo il redirect a meno che non si è settato il terzo parametro a false.
3.5.3.2.2 flash
flash(string $message, string $url, integer $pause)
Similmente, il metodo flash() è usato per direzionare un utente ad una nuova pagina dopo una certa operazione. Il metodo flash() si differenzia in quanto visualizza un messaggio prima di mandare l'utente ad un altro URL.
Il primo parametro conterrà il messaggio che verrà visualizzato, e il secondo parametro è un indirizzo relativo CakePHP. CakePHP visualizzerà il $message per $pause secondi prima di reindirizzare l'utente.
Per i messaggi flash in-page, consultare il metodo setFlash() del SessionComponent.
3.5.3.3 Callbacks
I controller di CakePHP utlizzano delle funzione di callback per inserire una logica prima o dopo che un'azione del controllor venga restituita.
beforeFilter()
Questa funzione è eseguita prima di ogni azione del controller. E' un posto utile dove controllare per una sessione attiva o controllare i permessi dell'utente.
beforeRender()
Chiamato dopo la logica delle azioni del controller, ma prima che la vista sia restituita. Questa funzione non è spesso utilizzata, ma può servire se si chiama render() manualmente prima della fine di una certa azione.
afterFilter()
Chiamata dopo ogni azione del controller.
afterRender()
Chiamata dopo che un'azione viene restituita.
CakePHP supporta inoltre callback relative allo scaffolding.
_beforeScaffold($method)
$method nome del metodo chiamato esempio index, edit, etc.
_afterScaffoldSave($method)
$method nome del metodo chiamato o edit o update.
_afterScaffoldSaveError($method)
$method nome del metodo chiamato o edit o update.
_scaffoldError($method)
$method nome del metodo chiamato esempio 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);
}
function index() {$o = $this->Orders->findAll($this->postConditions($this->data));$this->set('orders', $o);}
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')
));
/*Contents of $this->dataarray('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')));
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));
}
}
// controllers/comments_controller.phpclass CommentsController extends AppController {function latest() {return $this->Comment->find('all', array('order' => 'Comment.created DESC', 'limit' => 10));}}
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'];
}
// views/elements/latest_comments.ctp$comments = $this->requestAction('/comments/latest');foreach($comments as $comment) {echo $comment['Comment']['title'];}
We can then place that element anywhere at all to get the output using:
echo $this->element('latest_comments'); 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')); 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')); 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'); 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))); 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']
