3.4.3 A Classe Configuration

Ainda que poucas coisas precisem ser configuradas no CakePHP, às vezes é útil ter suas próprias regras de configuração para sua aplicação. No passado você definia valores de configuração customizados definindo variáveis ou constantes em alguns arquivos. Fazendo assim, você era forçado a incluir esse arquivo de configuração cada vez que precisasse usar aqueles valores.

A nova classe "Configure" do CakePHP pode ser usada para armazenar e retornar valores específicos da aplicação ou execução. Mas tenha cuidado! Esta classe permite que você armazene qualquer coisa para ser usada em outra parte do seu código: uma grande tentação para quebrar o padrão MVC para o qual o CakePHP foi projetado. O objetivo principal da classe Configure é manter centralizadas variáveis que podem ser partilhadas entre vários objetos. Se lembre de usar o lema "convenção e não configuração", e você não correrá o risco de quebrar a estrutura MVC que construímos.

Esta classe possui apenas uma instância e seus métodos podem ser chamados de qualquer parte dentro de sua aplicação, num contexto estático.

<?php Configure::read('debug'); ?>
  1. <?php Configure::read('debug'); ?>

3.4.3.1 Configure Methods

3.4.3.1.1 write

write(string $key, mixed $value)

Use write() para armazenar dados na configuração da aplicação.

Configure::write('Company.name','Pizza, Inc.');
Configure::write('Company.slogan','Pizza for your body and soul');
  1. Configure::write('Company.name','Pizza, Inc.');
  2. Configure::write('Company.slogan','Pizza for your body and soul');

o uso do ponto no parâmetro $key. Você pode usar essa notação para organizar sua configuração dentro dos grupos lógicos.

O exemplo acima poderia também ser escrito em uma única chamada:

Configure::write(
    'Company',array('name'=>'Pizza, Inc.','slogan'=>'Pizza for your body and soul')
);
  1. Configure::write(
  2. 'Company',array('name'=>'Pizza, Inc.','slogan'=>'Pizza for your body and soul')
  3. );

Você pode usar Configure::write('debug', $int) para alternar entre modos de produção e compilação no fly. Isso é recomendado especialmente para interações com AMF ou SOAP onde a informação do compilador pode causar problemas de sintaxe.

3.4.3.1.2 read

read(string $key = 'debug')

Used to read configuration data from the application. Defaults to CakePHP’s important debug value. If a key is supplied, the data is returned. Using our examples from write() above, we can read that data back:

Configure::read('Company.name');    //yields: 'Pizza, Inc.'
Configure::read('Company.slogan');  //yields: 'Pizza for your body and soul'
 
Configure::read('Company');
 
//yields: 
array('name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul');
  1. Configure::read('Company.name'); //yields: 'Pizza, Inc.'
  2. Configure::read('Company.slogan'); //yields: 'Pizza for your body and soul'
  3. Configure::read('Company');
  4. //yields:
  5. array('name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul');

3.4.3.1.3 delete

delete(string $key)

Utilizado para apagar informações de configuração do aplicativo.

Configure::delete('Company.name');
  1. Configure::delete('Company.name');

3.4.3.1.4 load

load(string $path)

Utilize este método para carregar informações de configuração de um arquivo específico.

// /app/config/messages.php:
<?php
$config['Company']['name'] = 'Pizza, Inc.';
$config['Company']['slogan'] = 'Pizza for your body and soul';
$config['Company']['phone'] = '555-55-55';
?>
 
<?php
Configure::load('messages');
Configure::read('Company.name');
?>
  1. // /app/config/messages.php:
  2. <?php
  3. $config['Company']['name'] = 'Pizza, Inc.';
  4. $config['Company']['slogan'] = 'Pizza for your body and soul';
  5. $config['Company']['phone'] = '555-55-55';
  6. ?>
  7. <?php
  8. Configure::load('messages');
  9. Configure::read('Company.name');
  10. ?>

Cada configuração chave-valor é representada no arquivo com o array $config. Quaisquer outras variáveis serão ignoradas pela função load().

3.4.3.1.5 version

version()

Returns the CakePHP version for the current application.

3.4.3.2 CakePHP Core Configuration Variables

The Configure class is used to manage a set of core CakePHP configuration variables. These variables can be found in app/config/core.php. Below is a description of each variable and how it affects your CakePHP application.

Configure Variable Description
debug Changes CakePHP debugging output.

0 = Production mode. No output.
1 = Show errors and warnings.
2 = Show errors, warnings, and SQL.
3 = Show errors, warnings, SQL, and complete controller dump.
App.baseUrl Un-comment this definition if you don’t plan to use Apache’s mod_rewrite with CakePHP. Don’t forget to remove your .htaccess files too.
Routing.admin Un-comment this definition if you’d like to take advantage of CakePHP admin routes. Set this variable to the name of the admin route you’d like to use. More on this later.
Cache.disable When set to true, caching is disabled site-wide.
Cache.check If set to true, enables view caching. Enabling is still needed in the controllers, but this variable enables the detection of those settings.
Session.save Tells CakePHP which session storage mechanism to use.

php = Use the default PHP session storage.
cake = Store session data in /app/tmp
database = store session data in a database table. Make sure to set up the table using the SQL file located at /app/config/sql/sessions.sql.
Session.table The name of the table (not including any prefix) that stores session information.
Session.database The name of the database that stores session information.
Session.cookie The name of the cookie used to track sessions.
Session.timeout Base session timeout in seconds. Actual value depends on Security.level.
Session.start Automatically starts sessions when set to true.
Session.checkAgent When set to false, CakePHP sessions will not check to ensure the user agent does not change between requests.
Security.level The level of CakePHP security. The session timeout time defined in 'Session.timeout' is multiplied according to the settings here.

Valid values:
'high' = x 10
'medium' = x 100
'low' = x 300

'high' and 'medium' also enable session.referer_check
Security.salt A random string used in security hashing.
Acl.classname, Acl.database Constants used for CakePHP’s Access Control List functionality. See the Access Control Lists chapter for more information.

Cache configuration is also found in core.php — We’ll be covering that later on, so stay tuned.

The Configure class can be used to read and write core configuration settings on the fly. This can be especially handy if you want to turn the debug setting on for a limited section of logic in your application, for instance.

3.4.3.3 Configuration Constants

While most configuration options are handled by Configure, there are a few constants that CakePHP uses during runtime.

Constant Description
LOG_ERROR Error constant. Used for differentiating error logging and debugging. Currently PHP supports LOG_DEBUG.