3.5.3.1 Interagindo com as views

set(string $var, mixed $value)

O método set() é a principal forma de enviar dados do seu controller para sua view. Um vez que você usou set(), a variável pode ser acessada na sua view.

<?php
    
// Primeiro você passa os dados do controller:

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

// Então, na view, você pode utilizar os dados:

Você selecionou a cor <?php echo $cor; ?> para colorizar o cake.

?>
  1. <?php
  2. // Primeiro você passa os dados do controller:
  3. $this->set('cor', 'pink');
  4. // Então, na view, você pode utilizar os dados:
  5. Você selecionou a cor <?php echo $cor; ?> para colorizar o cake.
  6. ?>

O método set() também pega um array associativo como seu primeiro parâmetro. Esse pode ser geralmente uma caminho rápido para atribuir um grupo de informações para a view. Perceba que os índices de seu array sofrerão inflection antes de serem atribuídos à view ('indice_com_underline' se torna 'indiceComUnderline', etc.):

<?php
    
$dados = array(
    'cor' => 'pink',
    'tipo' => 'açucar'’,
    'preco_base' => 23.95
);

// fazem $cor, $tipo, e $precoBase
// disponíveis na view:

$this->set($data);  

?>
  1. <?php
  2. $dados = array(
  3. 'cor' => 'pink',
  4. 'tipo' => 'açucar',
  5. 'preco_base' => 23.95
  6. );
  7. // fazem $cor, $tipo, e $precoBase
  8. // disponíveis na view:
  9. $this->set($data);
  10. ?>
render(string $action, string $layout, string $file)

O método render() é automaticamente chamado ao final de cada action do controller requisitada. Esse método executa toda a lógica da view (usando dados que você forneceu usando o método set()), insere a view dentro do layout e o serve de volta para o usuário final.

O arquivo de view padrão renderizado é determinado por convenção. Se a action buscar() do ReceitasController é requisitada, o arquivo de view /app/views/receitas/buscar.ctp será renderizado.

Ainda que o CakePHP vá automaticamente chamá-lo (a menos que você configure $this->autoRender para false) depois de cada lógica de action, você pode usá-lo para especificar um arquivo de view alternativo configurando o nome da action no controller usando $action. Você pode também especificar um arquivo alternativo um terceiro parâmetro, $file. Quando usar $file, lembre-se de utilizar um pouco das constantes globais do CakePHP (como a VIEWS).

O parâmetro $layout permite especificar o layout na qual a view é renderizada.

3.5.3.1.1 set

set(string $var, mixed $value)
  1. 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. 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);  

?>
  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)
  1. 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.