Configuring a CakePHP application is a piece of cake. After you have installed CakePHP, creating a basic web application requires only that you setup a database configuration.
There are, however, other optional configuration steps you can take in order to take advantage of CakePHP flexible architecture. You can easily add to the functionality inherited from the CakePHP core, configure additional/different URL mappings (routes), and define additional/different inflections.
CakePHP expects database configuration details to be in a file at app/Config/database.php. An example database configuration file can be found at app/Config/database.php.default. A finished configuration should look something like this:
<?php
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'cakephpuser',
'password' => 'c4k3roxx!',
'database' => 'my_cakephp_project',
'prefix' => ''
);
}
The $default connection array is used unless another connection is specified by the $useDbConfig property in a model. For example, if my application has an additional legacy database in addition to the default one, I could use it in my models by creating a new $legacy database connection array similar to the $default array, and by setting public $useDbConfig = 'legacy'; in the appropriate models.
Fill out the key/value pairs in the configuration array to best suit your needs.
Note
The prefix setting is for tables, not models. For example, if you create a join table for your Apple and Flavor models, you name it prefix_apples_flavors (not prefix_apples_prefix_flavors), and set your prefix setting to ‘prefix_’.
At this point, you might want to take a look at the CakePHP Conventions. The correct naming for your tables (and the addition of some columns) can score you some free functionality and help you avoid configuration. For example, if you name your database table big_boxes, your model BigBox, your controller BigBoxesController, everything just works together automatically. By convention, use underscores, lower case, and plural forms for your database table names - for example: bakers, pastry_stores, and savory_cakes.
It’s occasionally useful to be able to share MVC classes between applications on the same system. If you want the same controller in both applications, you can use CakePHP’s bootstrap.php to bring these additional classes into view.
By using App::build() in bootstrap.php we can define additional paths where CakePHP will look for classes:
<?php
App::build(array(
'Model' => array('/path/to/models', '/next/path/to/models'),
'Model/Behavior' => array('/path/to/behaviors', '/next/path/to/behaviors'),
'Model/Datasource' => array('/path/to/datasources', '/next/path/to/datasources'),
'Model/Datasource/Database' => array('/path/to/databases', '/next/path/to/database'),
'Model/Datasource/Session' => array('/path/to/sessions', '/next/path/to/sessions'),
'Controller' => array('/path/to/controllers', '/next/path/to/controllers'),
'Controller/Component' => array('/path/to/components', '/next/path/to/components'),
'Controller/Component/Auth' => array('/path/to/auths', '/next/path/to/auths'),
'Controller/Component/Acl' => array('/path/to/acls', '/next/path/to/acls'),
'View' => array('/path/to/views', '/next/path/to/views'),
'View/Helper' => array('/path/to/helpers', '/next/path/to/helpers'),
'Console' => array('/path/to/consoles', '/next/path/to/consoles'),
'Console/Command' => array('/path/to/commands', '/next/path/to/commands'),
'Console/Command/Task' => array('/path/to/tasks', '/next/path/to/tasks'),
'Lib' => array('/path/to/libs', '/next/path/to/libs'),
'Locale' => array('/path/to/locales', '/next/path/to/locales'),
'Vendor' => array('/path/to/vendors', '/next/path/to/vendors'),
'Plugin' => array('/path/to/plugins', '/next/path/to/plugins'),
));
Note
All additional path configuration should be done at the top of your application’s bootstrap.php. This will ensure that the paths are available for the rest of your application.
Each application in CakePHP contains a configuration file to determine CakePHP’s internal behavior. app/Config/core.php. This file is a collection of Configure class variable definitions and constant definitions that determine how your application behaves. Before we dive into those particular variables, you’ll need to be familiar with Configure, CakePHP’s configuration registry class.
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 the Error handler used to handle errors for your application. By default ErrorHandler::handleError() is used. It will display errors using Debugger, when debug > 0 and log errors with CakeLog when debug = 0.
Sub-keys:
Contains an array of settings to use for session configuration. The defaults key is used to define a default preset to use for sessions, any settings declared here will override the settings of the default config.
Sub-keys
The built in defaults are:
To define a custom session handler, save it at app/Model/Datasource/Session/<name>.php. Make sure the class implements CakeSessionHandlerInterface and set Session.handler to <name>
To use database sessions, run the app/Config/Schema/sessions.php schema using the cake shell command: cake schema create Sessions
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.
While most configuration options are handled by Configure, there are a few constants that CakePHP uses during runtime.
Error constant. Used for differentiating error logging and debugging. Currently PHP supports LOG_DEBUG.
CakePHP uses two cache configurations internally. _cake_model_ and _cake_core_. _cake_core_ is used to store file paths, and object locations. _cake_model_ is used to store schema descriptions, and source listings for datasources. Using a fast cache storage like APC or Memcached is recommended for these configurations, as they are read on every request. By default both of these configurations expire every 10 seconds when debug is greater than 0.
As with all cached data stored in Cache you can clear data using Cache::clear().
Despite few things needing to be configured in CakePHP, it’s sometimes useful to have your own configuration rules for your application. In the past you may have defined custom configuration values by defining variable or constants in some files. Doing so forces you to include that configuration file every time you needed to use those values.
CakePHP’s Configure class can be used to store and retrieve application or runtime specific values. Be careful, this class allows you to store anything in it, then use it in any other part of your code: a sure temptation to break the MVC pattern CakePHP was designed for. The main goal of Configure class is to keep centralized variables that can be shared between many objects. Remember to try to live by “convention over configuration” and you won’t end up breaking the MVC structure we’ve set in place.
This class can be called from anywhere within your application, in a static context:
<?php
Configure::read('debug');
Parameters: |
|
---|
Use write() to store data in the application’s configuration:
<?php
Configure::write('Company.name','Pizza, Inc.');
Configure::write('Company.slogan','Pizza for your body and soul');
Note
The dot notation used in the $key parameter can be used to organize your configuration settings into logical groups.
The above example could also be written in a single call:
<?php
Configure::write(
'Company', array('name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul')
);
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.
Parameters: |
|
---|
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:
<?php
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');
If $key is left null, all values in Configure will be returned.
Parameters: |
|
---|
Used to delete information from the application’s configuration:
<?php
Configure::delete('Company.name');
Returns the CakePHP version for the current application.
Parameters: |
|
---|
Attach a configuration reader to Configure. Attached readers can then be used to load configuration files. See Loading configuration files for more information on how to read configuration files.
Parameters: |
|
---|
Either check that a reader with a given name is attached, or get the list of attached readers.
Drops a connected reader object.
CakePHP comes with two built-in configuration file readers. PhpReader is able to read PHP config files, in the same format that Configure has historically read. IniReader is able to read ini config files. See the PHP documentation for more information on the specifics of ini files. To use a core config reader, you’ll need to attach it to Configure using Configure::config():
<?php
App::uses('PhpReader', 'Configure');
// Read config files from app/Config
Configure::config('default', new PhpReader());
// Read config files from another path.
Configure::config('default', new PhpReader('/path/to/your/config/files/'));
You can have multiple readers attached to Configure, each reading different kinds of configuration files, or reading from different types of sources. You can interact with attached readers using a few other methods on Configure. To see check which reader aliases are attached you can use Configure::configured():
<?php
// Get the array of aliases for attached readers.
Configure::configured();
// Check if a specific reader is attached
Configure::configured('default');
You can also remove attached readers. Configure::drop('default') would remove the default reader alias. Any future attempts to load configuration files with that reader would fail.
Parameters: |
|
---|
Once you’ve attached a config reader to Configure you can load configuration files:
<?php
// Load my_file.php using the 'default' reader object.
Configure::load('my_file', 'default');
Loaded configuration files merge their data with the existing runtime configuration in Configure. This allows you to overwrite and add new values into the existing runtime configuration. By setting $merge to true, values will not ever overwrite the existing configuration.
Parameters: |
|
---|
Dumps all or some of the data in Configure into a file or storage system supported by a config reader. The serialization format is decided by the config reader attached as $config. For example, if the ‘default’ adapter is a PhpReader, the generated file will be a PHP configuration file loadable by the PhpReader
Given that the ‘default’ reader is an instance of PhpReader. Save all data in Configure to the file my_config.php:
<?php
Configure::dump('my_config.php', 'default');
Save only the error handling configuration:
<?php
Configure::dump('error.php', 'default', array('Error', 'Exception'));
Configure::dump() can be used to either modify or overwrite configuration files that are readable with Configure::load()
New in version 2.2: Configure::dump() was added in 2.2.
Parameters: |
|
---|
You can also store runtime configuration values for use in a future request. Since configure only remembers values for the current request, you will need to store any modified configuration information if you want to use it in subsequent requests:
<?php
// Store the current configuration in the 'user_1234' key in the 'default' cache.
Configure::store('user_1234', 'default');
Stored configuration data is persisted in the Cache class. This allows you to store Configuration information in any storage engine that Cache can talk to.
Parameters: |
|
---|
Once you’ve stored runtime configuration, you’ll probably need to restore it so you can access it again. Configure::restore() does exactly that:
<?php
// restore runtime configuration from the cache.
Configure::restore('user_1234', 'default');
When restoring configuration information it’s important to restore it with the same key, and cache configuration as was used to store it. Restored information is merged on top of the existing runtime configuration.
Since configuration readers are an extensible part of CakePHP, you can create configuration readers in your application and plugins. Configuration readers need to implement the ConfigReaderInterface. This interface defines a read method, as the only required method. If you really like XML files, you could create a simple Xml config reader for you application:
<?php
// in app/Lib/Configure/XmlReader.php
App::uses('Xml', 'Utility');
class XmlReader implements ConfigReaderInterface {
public function __construct($path = null) {
if (!$path) {
$path = APP . 'Config' . DS;
}
$this->_path = $path;
}
public function read($key) {
$xml = Xml::build($this->_path . $key . '.xml');
return Xml::toArray($xml);
}
}
In your app/Config/bootstrap.php you could attach this reader and use it:
<?php
App::uses('XmlReader', 'Configure');
Configure::config('xml', new XmlReader());
...
Configure::load('my_xml');
The read() method of a config reader, must return an array of the configuration information that the resource named $key contains.
Defines the interface used by classes that read configuration data and store it in Configure
Parameters: |
|
---|
This method should load/parse the configuration data identified by $key and return an array of data in the file.
Thrown when errors occur when loading/storing/restoring configuration data. ConfigReaderInterface implementations should throw this error when they encounter an error.
Allows you to read configuration files that are stored as plain PHP files. You can read either files from your app/Config or from plugin configs directories by using plugin syntax. Files must contain a $config variable. An example configuration file would look like:
<?php
$config = array(
'debug' => 0,
'Security' => array(
'salt' => 'its-secret'
),
'Exception' => array(
'handler' => 'ErrorHandler::handleException',
'renderer' => 'ExceptionRenderer',
'log' => true
)
);
Files without $config will cause an ConfigureException
Load your custom configuration file by inserting the following in app/Config/bootstrap.php:
Configure::load(‘customConfig’);
Allows you to read configuration files that are stored as plain .ini files. The ini files must be compatible with php’s parse_ini_file function, and benefit from the following improvements
An example ini file would look like:
debug = 0
Security.salt = its-secret
[Exception]
handler = ErrorHandler::handleException
renderer = ExceptionRenderer
log = true
The above ini file, would result in the same end configuration data as the PHP example above. Array structures can be created either through dot separated values, or sections. Sections can contain dot separated keys for deeper nesting.
Cake’s naming conventions can be really nice - you can name your database table big_boxes, your model BigBox, your controller BigBoxesController, and everything just works together automatically. The way CakePHP knows how to tie things together is by inflecting the words between their singular and plural forms.
There are occasions (especially for our non-English speaking friends) where you may run into situations where CakePHP’s inflector (the class that pluralizes, singularizes, camelCases, and under_scores) might not work as you’d like. If CakePHP won’t recognize your Foci or Fish, you can tell CakePHP about your special cases.
You can use Inflector::rules() in the file app/Config/bootstrap.php to load custom inflections:
<?php
Inflector::rules('singular', array(
'rules' => array('/^(bil)er$/i' => '\1', '/^(inflec|contribu)tors$/i' => '\1ta'),
'uninflected' => array('singulars'),
'irregular' => array('spins' => 'spinor')
));
or:
<?php
Inflector::rules('plural', array('irregular' => array('phylum' => 'phyla')));
Will merge the supplied rules into the inflection sets defined in lib/Cake/Utility/Inflector.php, with the added rules taking precedence over the core rules.
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:
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 a handy place to use controller callbacks and define methods to be used by all of your controllers.