Controllers
Introduzione
Il controller è utilizzato per gestire la logica dell'applicazione. Normalmente un controller gestisce la logica relativa a un modello. Per esempio, se stai realizzando un sito per una panetteria online, avrai un RicetteController e un IngredientiController che gestiranno i modelli ricetta e ingrediente. In CakePHP, i controllers prendono il nome dei relativi modelli, al plurale.
Il modello Ricetta è controllato dal controller RicetteController, il modello Prodotto dal controller ProdottiController, e così via.
I controllers sono classi che estendono la classe di CakePHP AppController, che a sua volta estende la classe Controller. La classe AppController può essere definita in /app/app_controller.php, e può contenere metodi condivisi da tutti i controllers della tua applicazione. Estende la classe Controller, che è una classe standard di CakePHP.
I controllers includono tutti i metodi che normalmente chiameremo azioni. Le azioni sono dunque metodi del controller finalizzati a renderizzare le views (viste). Un'azione rappresenta un solo metodo del controller. CakePHP richiama le azioni di un determinato controller in base alle richieste provenienti dall'URL. Ritornando all'esempio della panetteria, il nostro RicetteController contiene le azioni mostra(), condividi() e cerca(). Il controller si trova in /app/controllers/ricette_controller.php contiene:
<?php
# /app/controllers/recipes_controller.php
class RecipesController extends AppController {
function mostra($id) {
//qui deve essere inserita la logica dell'azione..
}
function condividi($customer_id, $ricetta_id) {
//qui deve essere inserita la logica dell'azione..
}
function cerca($query) {
//qui deve essere inserita la logica dell'azione..
}
}
?>
<?php# /app/controllers/recipes_controller.phpclass RecipesController extends AppController {function mostra($id) {//qui deve essere inserita la logica dell'azione..}function condividi($customer_id, $ricetta_id) {//qui deve essere inserita la logica dell'azione..}function cerca($query) {//qui deve essere inserita la logica dell'azione..}}?>
Per imparare ad usare appieno le funzionalità dei controllers, passiamo ad esplorare alcuni attributi e metodi forniti da CakePHP.
Attributi della classe Controller
$name
Gli utenti di PHP4 dovrebbero porre in tutte in ogni controller la definizione dell'attributo $name. L'attributo $name deve corrispondere con il nome del controller. Normalmente questo nome corrisponde al plurale del modello principale a cui il controller fa riferimento. Questo accorgimento risolve alcuni problemi di PHP4 con i nomi delle classi, e aiuta CakePHP a usare i nomi corretti.
<?php
# esempio di utilizzo dell'attributo $name
class RicetteController extends AppController {
var $name = 'Ricette';
}
?>
<?php# esempio di utilizzo dell'attributo $nameclass RicetteController extends AppController {var $name = 'Ricette';}?>
$components, $helpers e $uses
Molto importanti sono gli attributi che definiscono quali helpers, components e models devono essere usati dal controller. Usando questi attributi, queste classi MVC saranno accessibili dal controller come variabili ($this->ModelName, per esempio).
Fai attenzione che ogni controller dispone di default di alcune classi, quindi non devi necessariamente configurarle ogni volta tutte.
In particolare i controllers hanno accesso alla classe del modello principale a cui sono associati. In nostro RicetteController è associato di default al modello Ricetta e vi accede tramite la variabile $this->Ricetta, mentre il nostro controller ProdottiController accede a sua volta al modello Prodotto tramite $this->Prodotto.
Gli Helper Html e Session sono disponibili di default, come anche il componente SessionComponent. I dettagli su queste classi saranno spiegati più avanti in questo manuale.
Osserva come puoi utilizzare le classi associate al controller in CakePHP.
<?php
class RicetteController extends AppController {
var $name = 'Ricette';
var $uses = array('Ricetta', 'User');
var $helpers = array('Html', 'Ajax');
var $components = array('Session', 'Email');
}
?>
<?phpclass RicetteController extends AppController {var $name = 'Ricette';var $uses = array('Ricetta', 'User');var $helpers = array('Html', 'Ajax');var $components = array('Session', 'Email');}?>
Quando definisci questi attributi, stai attendo a includere anche le classi normalmente incluse di default (come l'helper Html, ad esempio) se intendi utilizzarle. Infatti quando definisci esplicitamente questi attributi, sovrascrivi di fatto le impostazioni di default.
Attributi della pagina: $layout e $pageTitle
In CakePHP c'è un set di attributi che ti permettono di controllare il modo in cui le viste sono inserite nel layout.
L'attributo $layout può essere impostato con il nome di un layout presente nella cartella /app/views/layouts. Il valore della variabile $layout deve coincidere con il nome del file da utilizzare, senza l'estensione .ctp. Se non imposti la variabile, CakePHP utilizza il layout default. Se non ne hai definito uno in /app/views/default.ctp, CakePHP utilizza il suo layout predefinito interno.
<?php
# Usa $layout per utilizzare un layout personalizzato
class RecipesController extends AppController {
function quickSave() {
$this->layout = 'ajax';
}
}
?>
<?php# Usa $layout per utilizzare un layout personalizzatoclass RecipesController extends AppController {function quickSave() {$this->layout = 'ajax';}}?>
L'attributo $pageTitle del controller ti permette di impostare il titolo visualizzato nella pagina. Perché tutto funzioni, il layout deve contenere una variabile $title_for_layout, preferibilmente richiamata nel tag <title> della sezione head della pagina HTML.
Basta impostare $pageTitle con la stringa da visualizzare nel tag <title> del documento.
L'attributo Parametri ($params)
I parametri inviati al controller al momento della richiesta sono accessibili tramite la variabile $this->params. Questa variabile serve appunto per raccogliere le informazioni inviate al momento della richiesta. L'utilizzo più comune di $this->params consiste nell'accedere alle informazioni inviate al controller tramite una richiesta GET o POST.
form
$this->params['form']
$this->params['form']
Any POST data from any form is stored here, including information also found in $_FILES.
bare
$this->params['bare']
$this->params['bare']
Stores 1 if the current layout is empty, 0 if not.
isAjax
$this->params['ajax']
$this->params['ajax']
Stores 1 if the current layout is set to ‘ajax’, 0 if not. This variable is only set if the RequestHandler Component is being used in the controller.
controller
$this->params['controller']
$this->params['controller']
Stores the name of the current controller handling the request. For example, if the URL /posts/view/1 was requested, $this->params['controller'] would equal "posts".
action
$this->params['action']
$this->params['action']
Stores the name of the current action handling the request. For example, if the URL /posts/view/1 was requested, $this->params['action'] would equal "view".
pass
$this->params['pass']
$this->params['pass']
Stores the GET query string passed with the current request. For example, if the URL /posts/view/?var1=3&var2=4 was requested, $this->params['pass'] would equal "?var1=3&var2=4".
url
$this->params['url']
$this->params['url']
Stores the current URL requested, along with key-value pairs of get variables. For example, if the URL /posts/view/?var1=3&var2=4 was called, $this->params['url'] would contain:
[url] => Array
(
[url] => posts/view
[var1] => 3
[var2] => 4
)
[url] => Array([url] => posts/view[var1] => 3[var2] => 4)
data
$this->data
$this->data
Used to handle POST data sent from the FormHelper forms to the controller.
<?php
// The FormHelper is used to create a form element:
$form->text('User.first_name');
// When rendered, it looks something like:
<input name="data[User][first_name]" value="" type="text" />
// When the form is submitted to the controller via POST,
// the data shows up in $this->data.
//The submitted first name can be found here:
$this->data['User']['first_name'];
?>
<?php// The FormHelper is used to create a form element:$form->text('User.first_name');// When rendered, it looks something like:<input name="data[User][first_name]" value="" type="text" />// When the form is submitted to the controller via POST,// the data shows up in $this->data.//The submitted first name can be found here:$this->data['User']['first_name'];?>
Other Attributes
While you can check out the details for all controller attributes in the API, there are other controller attributes that merit their own sections in the manual.
The $cacheAction attribute aids in caching views, and the $paginate attribute is used to set pagination defaults for the controller. For more information on how to use these attributes, check out their respective sections later on in this manual.
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.
Interacting with Views
set
set(string $var, mixed $value)
set(string $var, mixed $value)
The set() method is the main way to get 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 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.?>
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. Note that your array keys will be inflected before they get 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);
?>
<?php$data = array('color' => 'pink','type' => 'sugar','base_price' => 23.95);//make $color, $type, and $basePrice//available to the view:$this->set($data);?>
render
render(string $action, string $layout, string $file)
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.
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. You can also specify an alternate view 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.
Flow Control
redirect
redirect(string $url, integer $status, boolean $exit)
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.
<?php
function placeOrder() {
//Logic for finalizing order goes here
if($success) {
$this->redirect('/orders/thanks');
} else {
$this->redirect('/orders/confirm');
}
}
?>
<?phpfunction placeOrder() {//Logic for finalizing order goes hereif($success) {$this->redirect('/orders/thanks');} else {$this->redirect('/orders/confirm');}}?>
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.
flash
flash(string $message, string $url, integer $pause)
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.
Callbacks
CakePHP controllers come fitted with callbacks you can use to insert logic just before or after controller actions are rendered.
This function is executed before every action in the controller. Its a handy place to check for an active session or inspect user permissions.
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.
Called after every controller action.
Called after an action has been rendered.
Other Useful Methods
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.
referrer
Returns the referring URL for the current request.
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.
postConditions
postConditions(array $data, mixed $op, string $bool, boolean $exclusive)
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 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.
paginate
This method is used for paginating results fetched by your models. You can specify page sizes, model find conditions and more. Details on this method follow later. Check out the pagination chapter later on in this manual.
requestAction
requestAction(string $url, array $options)
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). If the $options array includes a 'return' value, AutoRender is automatically set to true for the controller action, having requestAction hand you back a fully rendered view.
Note: while you can use requestAction() to retrieve a fully rendered view, the performance hit you take on running through the whole view layer another time isn't often worth it. The requestAction() method is best used in conjunction with elements–as a way to fetch business logic for an element before rendering.
First, let's look at how to get data from a controller action. First, we need to set up a controller action that returns some data we might need in various places throughout the application:
// Here is our simple controller:
class UsersController extends AppController {
function getUserList() {
return $this->User->findAll('User.active = 1');
}
}
// Here is our simple controller:class UsersController extends AppController {function getUserList() {return $this->User->findAll('User.active = 1');}}
Imagine that we needed to create a simple table showing the active users in the system. Instead of duplicating list-generating code in another controller, we can get the data from UsersController->getUserList() instead by using requestAction().
class ProductsController extends AppController {
function showUserProducts() {
$this->set(
'users',
$this->requestAction('/users/getUserList')
);
// Now the $users variable in the view will have the data from
// UsersController::getUserList().
}
}
class ProductsController extends AppController {function showUserProducts() {$this->set('users',$this->requestAction('/users/getUserList'));// Now the $users variable in the view will have the data from// UsersController::getUserList().}}
If you have an element in your application that is not static, you might want to use requestAction() to grab controller-like logic for the element as you inject it into your views. While elements always have access to any view variables the controller has passed, this is one way to get element data from another controller.
If you have created a controller action that supplies the logic needed, you can grab that data and pass it to the second parameter of the view's renderElement() method using requestAction().
renderElement(
'users',
$this->requestAction('/users/getUserList')
);
?>
<?phpecho $this->renderElement('users',$this->requestAction('/users/getUserList'));?>
If the $options array contains a 'return' value, the controller action is rendered inside an empty layout and returned. In this way, the requestAction() function is also useful in Ajax situations where a small element of a view needs to be populated before or during an Ajax update.

login to add a comment