Table of Contents : Manual

Configuração

 

Configuração da base de dados

O CakePHP espera que os detalhes de configuração da base de dados estejam no arquivo app/config/database.php. Um exemplo de configuração da base de dados pode ser encontrado em app/config/database.php.default.

var $default = array('driver'      => 'mysql',
                     'persistent'  => false,
                     'host'        => 'localhost',
                     'login'       => 'cakephpuser',
                     'password'    => 'c4k3roxx!',
                     'database'    => 'my_cakephp_project',
                     'prefix'      => '');
  1. var $default = array('driver' => 'mysql',
  2. 'persistent' => false,
  3. 'host' => 'localhost',
  4. 'login' => 'cakephpuser',
  5. 'password' => 'c4k3roxx!',
  6. 'database' => 'my_cakephp_project',
  7. 'prefix' => '');

A conexão $default é usada a menos que outra configuração seja especificada pela propriedade $useDbConfig em um modelo. Por exemplo, se minha aplicação tiver uma base de dados adicional do legacy além do padrão, eu poderia usá-la em meus modelos criando uma nova conexão da base de dados de $legacy similar a configuração $default, e ajustando a var $useDbConfig = ‘legacy’; nos modelos apropriados.

Preencha corretamente os pares de chave/valor na configuração para atender melhor às suas necessidades.

Chave Valor
driver O nome do driver da base de dados para esta configuração. Exemplos: mysql, postgres, sqlite, pear-drivername, adodb-drivername, mssql, oracle, ou odbc.
persistent Se usará ou não uma conexão persistente com a base de dados.
host O nome do servidor da base de dados (ou endereço IP).
login O usuário desta conta.
password A senha desta conta.
database O nome da base de dados que esta conexão irá usar.
prefix (opcional) Esta string será adicionada como prefixo no nome de todas tabelas de sua base de dados. Se suas tabelas não possuem prefixo, deixe esta string vazia.
port (opcional) A porta TCP ou socket Unix usado para conectar com o servidor.
encoding Indica qual caractere definido será usado para enviar indicações SQL ao servidor.
schema Usado em instalações de base de dados PostgreSQL para especificar qual schema usar.

Note que as configurações de prefixo são para as tabelas, não para os modelos. Por exemplo, se você criou um relacionamento entre as tabelas Apple e Flavor, o nome será prefixo_apples_flavors (não prefixo_apples_prefixo_flavors), isso se sua opção de prefixo estiver como 'prefixo_'.

A partir deste ponto, você deve dar uma olhada nas Convenções CakePHP, mostradas neste manual. A nomenclatura correta para suas tabelas (e o nome de algumas colunas) pode livrar de algumas implementações e configurações desnecessárias.

Core Configuration

A configuração da aplicação no CakePHP é encontrada no arquivo /app/config/core.php. Este arquivo é uma coleção de definições de variáveis e constantes da classe Configure, que determinam como sua aplicação se comporta. Antes de mergulharmos nessas variáveis em particular, você precisará familiarizar-se com o "Configure", a classe registrada de configuração do CakePHP.

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'); ?>

Configure Methods

write
write(string $key, mixed $value)
  1. write(string $key, mixed $value)

Use write() to store data in the application’s configuration.

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');

Note the usage of dot notation in the $key parameter. You can use this notation to organize your configuration into logical groups.

The above example could also be written in a single call:

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. );

You can use Configure::write(‘debug’, $int) to switch between debug and production modes on the fly. This is especially handy for AMF or SOAP interactions where debugging information can cause parsing problems.

read
read(string $key = 'debug')
  1. 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');
delete
delete(string $key)
  1. delete(string $key)

Used to delete information from the application’s configuration.

Configure::delete('Company.name');
  1. Configure::delete('Company.name');
load
load(string $path)
  1. load(string $path)

Use this method to load configuration information from a specific file.

// /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. ?>

Note that every configure key-value pair is represented in the file with the $config array. Any other variables in the file will be ignored by the load() function.

version
version()
  1. version()

Returns the CakePHP version for the current application.

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’s usage 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
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.

Note: 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.

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.

Configuração de rotas (routes)

Rotas é uma funcionalidade que mapeia URLs em ações do controller. Foi adicionado ao CakePHP para tornal URL amigáveies mais configuráveois e flexíveis. Não é obrigatório o uso do mod_rewrite para usar rotas, mas usando-o fará sua barra de endereços muito mais limpa e arrumada.

Rotas no CakePHP 1.2 foi ampliada e pode ser muito mais poderosa.

Antes de você aprender sobre como configurar suas próprias rotas, você deveria saber que o CakePHP vem configurado com um conjunto de rotas padrão. A configuração padrão de rotas do CakePHP deixará as URLs mais bonitas para qualquer aplicação. Você pode acessar diretamente uma ação via URL colocando seu nome na requisição. Você pode também passar paramêtros para suas ações no controller usando a própria URL.

    URL para a rota padrão: 
    http://example.com/controller/action/param1/param2/param3
  1. URL para a rota padrão:
  2. http://example.com/controller/action/param1/param2/param3

A URL /noticias/ler mapeia para a ação ler() do controller Noticias (NoticiasController), e /produtos/verInformacoes mapeia para a ação view_informacoes() do controller Produto (ProdutosController). Se nenhuma ação é especificada na URL, a ação index() será chamada.

A rota padrão também permite passar parâmetros para as ações usando a URL. Uma requisição /noticias/ler/12 seria equivalente a chamar o método ler(12) no controller Noticias (NoticiasController), por exemplo.

Uma novidade no CakePHP 1.2 é a possibilidade de usar parâmetros nomeados. Você pode nomear parâmetros e enviar seus valores usando a URL. Uma requisição /noticias/ler/titulo:primeira+noticia/categoria:esportes teria como resultado uma chamada a ação ler() do controller Noticias (NoticiasController). Nesta ação, você encontraria os valores dos parâmetros título e categoria dentro de $this->passedArgs['titulo'] e $this->passedArgs['categoria'] respectivamente.

Alguns exemplos para a rota padrão:

URL mapeadas para as ações dos controladores, usando rotas padrão:
    
URL: /monkeys/jump
Mapeado para: MonkeysController->jump();
 
URL: /products
Mapeado para: ProductsController->index();
 
URL: /tasks/view/45
Mapeado para: TasksController->view(45);
 
URL: /donations/view/recent/2001
Mapeado para: DonationsController->view('recent', '2001');

URL: /contents/view/chapter:models/section:associations
Mapeado para: ContentsController->view();
$this->passedArgs['chapter'] = 'models';
$this->passedArgs['section'] = 'associations';
  1. URL mapeadas para as ações dos controladores, usando rotas padrão:
  2. URL: /monkeys/jump
  3. Mapeado para: MonkeysController->jump();
  4. URL: /products
  5. Mapeado para: ProductsController->index();
  6. URL: /tasks/view/45
  7. Mapeado para: TasksController->view(45);
  8. URL: /donations/view/recent/2001
  9. Mapeado para: DonationsController->view('recent', '2001');
  10. URL: /contents/view/chapter:models/section:associations
  11. Mapeado para: ContentsController->view();
  12. $this->passedArgs['chapter'] = 'models';
  13. $this->passedArgs['section'] = 'associations';

Definindo suas próprias rotas permite você definir como sua aplicação irá responder a uma dada URL. Defina suas próprias rotas no arquivo /app/config/routes.php usando o método Router::connect().

O método connect() recebe três parâmetros: a URL que você deseja casar, o valor padrão para os elementos de rota, e regras de expressões regulares para ajudar a encontrar elementos na URL.

O formato básico para uma definição de rota é:

Router::connect(
    'URL',
    array('paramName' => 'defaultValue'),
    array('paramName' => 'matchingRegex')
)
  1. Router::connect(
  2. 'URL',
  3. array('paramName' => 'defaultValue'),
  4. array('paramName' => 'matchingRegex')
  5. )

The first parameter is used to tell the router what sort of URL you’re trying to control. The URL is a normal slash delimited string, but can also contain a wildcard (*) or custom route elements (URL elements prefixed with a colon). Using a wildcard tells the router what sorts of URLs you want to match, and specifying route elements allows you to gather parameters for your controller actions.

Once you’ve specified a URL, you use the last two parameters of connect() to tell CakePHP what to do with a request once it has been matched. The second parameter is an associative array. The keys of the array should be named after the route elements in the URL, or the default elements: :controller, :action, and :plugin. The values in the array are the default values for those keys. Let’s look at some basic examples before we start using the third parameter of connect().

Router::connect(
    '/pages/*',
    array('controller' => 'pages', 'action' => 'display')
);
  1. Router::connect(
  2. '/pages/*',
  3. array('controller' => 'pages', 'action' => 'display')
  4. );

This route is found in the routes.php file distributed with CakePHP (line 40). This route matches any URL starting with /pages/ and hands it to the display() method of the PagesController(); The request /pages/products would be mapped to PagesController->display(‘products’), for example.

Router::connect(
    '/government',
    array('controller' => 'products', 'action' => 'display', 5)
);
  1. Router::connect(
  2. '/government',
  3. array('controller' => 'products', 'action' => 'display', 5)
  4. );

This second example shows how you can use the second parameter of connect() to define default parameters. If you built a site that features products for different categories of customers, you might consider creating a route. This allows you link to /government rather than /products/display/5.

For additional flexibility, you can specify custom route elements. Doing so gives you the power to define places in the URL where parameters for controller actions should lie. When a request is made, the values for these custom route elements are found in $this->params of the controller. This is different than named parameters are handled, so note the difference: named parameters (/controller/action/name:value) are found in $this->passedArgs, whereas custom route element data is found in $this->params. When you define a custom route element, you also need to specify a regular expression - this tells CakePHP how to know if the URL is correctly formed or not.

Router::connect(
    '/:controller/:id',
    array('action' => 'view'),
    array('id' => '[0-9]+')
);
  1. Router::connect(
  2. '/:controller/:id',
  3. array('action' => 'view'),
  4. array('id' => '[0-9]+')
  5. );

This simple example illustrates how to create a quick way to view models from any controller by crafting a URL that looks like /controllername/id. The URL provided to connect() specifies two route elements: :controller and :id. The :controller element is a CakePHP default route element, so the router knows how to match and identify controller names in URLs. The :id element is a custom route element, and must be further clarified by specifying a matching regular expression in the third parameter of connect(). This tells CakePHP how to recognize the ID in the URL as opposed to something else, such as an action name.

Once this route has been defined, requesting /apples/5 is the same as requesting /apples/view/5. Both would call the view() method of the ApplesController. Inside the view() method, you would need to access the passed ID at $this->params[‘id’].

One more example, and you’ll be a routing pro.

Router::connect(
    '/:controller/:year/:month/:day',
    array('action' => 'index', 'day' => null),
    array(
        'year' => '[12][0-9]{3}',
        'month' => '(0[1-9]|1[012])',
        'day' => '(0[1-9]|[12][0-9]|3[01])'
    )
);
  1. Router::connect(
  2. '/:controller/:year/:month/:day',
  3. array('action' => 'index', 'day' => null),
  4. array(
  5. 'year' => '[12][0-9]{3}',
  6. 'month' => '(0[1-9]|1[012])',
  7. 'day' => '(0[1-9]|[12][0-9]|3[01])'
  8. )
  9. );

This is rather involved, but shows how powerful routes can really become. The URL supplied has four route elements. The first is familiar to us: it’s a default route element that tells CakePHP to expect a controller name.

Next, we specify some default values. Regardless of the controller, we want the index() action to be called. We set the day parameter (the fourth element in the URL) to null to flag it as being optional.

Finally, we specify some regular expressions that will match years, months and days in numerical form.

Once defined, this route will match /articles/2007/02/01, /posts/2004/11/16, and /products/2001/05 (remember that the day parameter is optional?), handing the requests to the index() actions of their respective controllers, with the custom date parameters in $this->params.

Inflexões personalizadas

As convenções de nomenclatura do Cake podem ser realmente legais. Você pode nomear sua tabela big_boxes, seu model BigBox, seu controller BigBoxesController e tudo isso funciona em conjunto automaticamente. A maneira que o CakePHP usa para associar todas juntas é através da utilização de inflections (inflexões), que transformam as palavras do singular em plural e vice-versa.

Existem ocasiões (especialmente para nossos amigos que não falam inglês - nosso caso), onde você pode rodar o inflector do CakePHP (a classe que pluraliza, singulariza, camelCases e under_scores) e não funcionar como você gostaria. Se o CakePHP não reconhecer seu Foci ou Fish, editando o arquivo de configuração personalizada de inflexões você poderá indicar seus casos especiais. O arquivo de configuração é encontrado em /app/config/inflections.php.

Neste arquivo, você irá encontrar seis variáveis. Cada uma permite você fazer o ajuste fino das inflections do CakePHP.

Variáveis do inflections.php Descrição
$pluralRules Este array contém regras de expressões regulares para pluralizar casos especiais. A chave do array são os patterns e o valor são as substituições.
$uninflectedPlural Um array que contém palavras que não precisam ser alteradas quando passadas para o plural (lápis, etc.).
$irregularPlural Um array que contém palavras e seus plurais. A chave do array contém a forma no singular e o valor a forma no plural. Este array deve ser usado para guardar palavras que não seguem as definições em $pluralRules.
$singularRules Similar a $pluralRules, contém as regras para singularizar as palavras.
$uninflectedSingular Similar a $uninflectedPlural, contém as palavras que não contém forma no singular. Por padrão, este array tem o mesmo valor de $uninflectedPlural.
$irregularSingular Similar a $irregularPlural, contém as palavras que possuem apenas a forma singular.

Bootstrapping CakePHP

If you have any additional configuration needs, use CakePHP’s bootstrap file, found in /app/config/bootstrap.php. This file is executed just after CakePHP’s core bootstrapping.

This file is ideal for a number of common bootstrapping tasks:

  • Defining convenience functions
  • Registering global constants
  • Defining additional model, view, and controller paths

Be careful to maintain the MVC software design pattern when you add things to the bootstrap file: it might be tempting to place formatting functions there in order to use them in your controllers.

Resist the urge. You’ll be glad you did later on down the line.

You might also consider placing things in the AppController class. This class is a parent class to all of the controllers in your application. AppController is handy place to use controller callbacks and define methods to be used by all of your controllers.