Configuration
While conventions remove the need to configure all of CakePHP, you’ll still needto configure a few things like your database credentials.
Additionally, there are optional configuration options that allow you to swapout default values & implementations with ones tailored to your application.
Configuring your Application
Configuration is generally stored in either PHP or INI files, and loaded duringthe application bootstrap. CakePHP comes with one configuration file by default,but if required you can add additional configuration files and load them inyour application’s bootstrap code. Cake\Core\Configure
is usedfor global configuration, and classes like Cache
provide setConfig()
methods to make configuration simple and transparent.
The application skeleton features a config/app.php file which should containconfiguration that doesn’t vary across the various environments your applicationis deployed in. The config/app_local.php file should contain theconfiguration data that varies between environments and shouldn’t be checkedinto version control. Both of these files reference environment variablesthrough the env()
function that enables configuration values to set thoughthe server environment.
Loading Additional Configuration Files
If your application has many configuration options it can be helpful to splitconfiguration into multiple files. After creating each of the files in yourconfig/ directory you can load them in bootstrap.php:
- use Cake\Core\Configure;
- use Cake\Core\Configure\Engine\PhpConfig;
- Configure::setConfig('default', new PhpConfig());
- Configure::load('app', 'default', false);
- Configure::load('other_config', 'default');
Environment Variables
Many modern cloud providers, like Heroku, let you define environmentvariables for configuration data. You can configure your CakePHP throughenvironment variables in the 12factor app style.Environment variables allow your application to require less state making yourapplication easier to manage when it is deployed across a number ofenvironments.
As you can see in your app.php, the env()
function is used to readconfiguration from the environment, and build the application configuration.CakePHP uses DSN strings for databases, logs, email transports and cacheconfigurations allowing you to easily vary these libraries in each environment.
For local development, CakePHP leverages dotenv to allow easy local development usingenvironment variables. You will see a config/.env.example
in yourapplication. By copying this file into config/.env
and customizing thevalues you can configure your application.
You should avoid committing the config/.env
file to your repository andinstead use the config/.env.example
as a template with placeholder values soeveryone on your team knows what environment variables are in use and whatshould go in each one.
Once your environment variables have been set, you can use env()
to readdata from the environment:
- $debug = env('APP_DEBUG', false);
The second value passed to the env function is the default value. This valuewill be used if no environment variable exists for the given key.
General Configuration
Below is a description of the variables and how they affect your CakePHPapplication.
- debug
- Changes CakePHP debugging output.
false
= Production mode. No errormessages, errors, or warnings shown.true
= Errors and warnings shown. - App.namespace
- The namespace to find app classes under.
Note
When changing the namespace in your configuration, you will alsoneed to update your composer.json file to use this namespaceas well. Additionally, create a new autoloader by runningphp composer.phar dumpautoload
.
- App.baseUrl
- Un-comment this definition if you don’t plan to use Apache’smod_rewrite with CakePHP. Don’t forget to remove your .htaccessfiles too.
- App.base
- The base directory the app resides in. If
false
thiswill be auto detected. If notfalse
, ensure your string startswith a / and does NOT end with a /. E.g., /basedir is a validApp.base. Otherwise, the AuthComponent will not work properly. - App.encoding
- Define what encoding your application uses. This encodingis used to generate the charset in the layout, and encode entities.It should match the encoding values specified for your database.
- App.webroot
- The webroot directory.
- App.wwwRoot
- The file path to webroot.
- App.fullBaseUrl
- The fully qualified domain name (including protocol) to your application’sroot. This is used when generating absolute URLs. By default this valueis generated using the
$SERVER
environment. However, you should define itmanually to optimize performance or if you are concerned about peoplemanipulating theHost
header.In a CLI context (from shells) the _fullBaseUrl cannot be read from $_SERVER,as there is no webserver involved. You do need to specify it yourself ifyou do need to generate URLs from a shell (e.g. when sending emails). - App.imageBaseUrl
- Web path to the public images directory under webroot. If you are usinga CDN you should set this value to the CDN’s location.
- App.cssBaseUrl
- Web path to the public css directory under webroot. If you are usinga CDN you should set this value to the CDN’s location.
- App.jsBaseUrl
- Web path to the public js directory under webroot. If you are usinga CDN you should set this value to the CDN’s location.
- App.paths
- Configure paths for non class based resources. Supports the
plugins
,templates
,locales
subkeys, which allow the definitionof paths for plugins, view templates and locale files respectively. - App.uploadedFilesAsObjects
- Defines whether uploaded files are being represented as objects (
true
),or arrays (false
). This option is being treated as disabled by default.See the File Uploads section in the Request &Response Objects chapter for more information. - Security.salt
- A random string used in hashing. This value is also used as theHMAC salt when doing symetric encryption.
- Asset.timestamp
Appends a timestamp which is last modified time of the particularfile at the end of asset files URLs (CSS, JavaScript, Image) whenusing proper helpers. Valid values:
- (bool)
false
- Doesn’t do anything (default) - (bool)
true
- Appends the timestamp when debug istrue
- (string) ‘force’ - Always appends the timestamp.
- (bool)
- Asset.cacheTime
- Sets the asset cache time. This determines the http header
Cache-Control
’smax-age
, and the http header’sExpire
’s time for assets.This can take anything that you version of php’s strtotime function can take.The default is+1 day
.
Using a CDN
To use a CDN for loading your static assets, change App.imageBaseUrl
,App.cssBaseUrl
, App.jsBaseUrl
to point the CDN URI, for example:https://mycdn.example.com/
(note the trailing /
).
All images, scripts and styles loaded via HtmlHelper will prepend the absoluteCDN path, matching the same relative path used in the application. Please notethere is a specific use case when using plugin based assets: plugins will notuse the plugin’s prefix when absolute …BaseUrl
URI is used, for example Bydefault:
$this->Helper->assetUrl('TestPlugin.logo.png')
resolves totest_plugin/logo.png
If you set App.imageBaseUrl
to https://mycdn.example.com/
:
$this->Helper->assetUrl('TestPlugin.logo.png')
resolves tohttps://mycdn.example.com/logo.png
.
Database Configuration
See the Database Configuration for informationon configuring your database connections.
Caching Configuration
See the Caching Configuration for information onconfiguring caching in CakePHP.
Error and Exception Handling Configuration
See the Error and Exception Configuration forinformation on configuring error and exception handlers.
Logging Configuration
See the Logging Configuration for information on configuring logging inCakePHP.
Email Configuration
See the Email Configuration for information onconfiguring email presets in CakePHP.
Session Configuration
See the Session Configuration for information on configuring sessionhandling in CakePHP.
Routing configuration
See the Routes Configuration for more informationon configuring routing and creating routes for your application.
Additional Class Paths
Additional class paths are setup through the autoloaders your application uses.When using composer
to generate your autoloader, you could do the following,to provide fallback paths for controllers in your application:
- "autoload": {
- "psr-4": {
- "App\\Controller\\": "/path/to/directory/with/controller/folders/",
- "App\\": "src/"
- }
- }
The above would setup paths for both the App
and App\Controller
namespace. The first key will be searched, and if that path does not contain theclass/file the second key will be searched. You can also map a single namespaceto multiple directories with the following:
- "autoload": {
- "psr-4": {
- "App\\": ["src/", "/path/to/directory/"]
- }
- }
Plugin, View Template and Locale Paths
Since plugins, view templates and locales are not classes, they cannot have anautoloader configured. CakePHP provides three Configure variables to setup additionalpaths for these resources. In your config/app.php you can set these variables:
- return [
- // More configuration
- 'App' => [
- 'paths' => [
- 'plugins' => [
- ROOT . DS . 'plugins' . DS,
- '/path/to/other/plugins/'
- ],
- 'templates' => [
- ROOT . 'templates' . DS,
- ROOT . 'templates2' . DS
- ],
- 'locales' => [
- ROOT . 'resources' . DS . 'locales' . DS
- ]
- ]
- ]
- ];
Paths should end with a directory separator, or they will not work properly.
Inflection Configuration
See the Inflection Configuration docs for more information.
Configure Class
CakePHP’s Configure class can be used to store and retrieveapplication or runtime specific values. Be careful, this classallows you to store anything in it, then use it in any other partof your code: a sure temptation to break the MVC pattern CakePHPwas designed for. The main goal of Configure class is to keepcentralized variables that can be shared between many objects.Remember to try to live by “convention over configuration” and youwon’t end up breaking the MVC structure CakePHP provides.
Writing Configuration data
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');
Note
The dot notation used in the $key
parameter can be used toorganize your configuration settings into logical groups.
The above example could also be written in a single call:
- Configure::write('Company', [
- 'name' => 'Pizza, Inc.',
- 'slogan' => 'Pizza for your body and soul'
- ]);
You can use Configure::write('debug', $bool)
to switch between debug andproduction modes on the fly. This is especially handy for JSON interactionswhere debugging information can cause parsing problems.
Reading Configuration Data
Used to read configuration data from the application. If a key is supplied, thedata is returned. Using our examples from write() above, we can read that databack:
- // Returns 'Pizza Inc.'
- Configure::read('Company.name');
- // Returns 'Pizza for your body and soul'
- Configure::read('Company.slogan');
- Configure::read('Company');
- // Returns:
- ['name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul'];
- // Returns 'fallback' as Company.nope is undefined.
- Configure::read('Company.nope', 'fallback');
If $key
is left null, all values in Configure will be returned.
Reads configuration data just like Cake\Core\Configure::read
but expects to find a key/value pair. In case the requested pair does notexist, a RuntimeException
will be thrown:
- Configure::readOrFail('Company.name'); // Yields: 'Pizza, Inc.'
- Configure::readOrFail('Company.geolocation'); // Will throw an exception
- Configure::readOrFail('Company');
- // Yields:
- ['name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul'];
Checking to see if Configuration Data is Defined
Used to check if a key/path exists and has non-null value:
- $exists = Configure::check('Company.name');
Deleting Configuration Data
Used to delete information from the application’s configuration:
- Configure::delete('Company.name');
Reading & Deleting Configuration Data
Read and delete a key from Configure. This is useful when you want tocombine reading and deleting values in a single operation.
Consumes configuration data just like Cake\Core\Configure::consume
but expects to find a key/value pair. In case the requested pair does notexist, a RuntimeException
will be thrown:
- Configure::consumeOrFail('Company.name'); // Yields: 'Pizza, Inc.'
- Configure::consumeOrFail('Company.geolocation'); // Will throw an exception
- Configure::consumeOrFail('Company');
- // Yields:
- ['name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul'];
Reading and writing configuration files
CakePHP comes with two built-in configuration file engines.Cake\Core\Configure\Engine\PhpConfig
is able to read PHP configfiles, in the same format that Configure has historically read.Cake\Core\Configure\Engine\IniConfig
is able to read ini configfiles. See the PHP documentation for moreinformation on the specifics of ini files. To use a core config engine, you’llneed to attach it to Configure using Configure::config()
:
- use Cake\Core\Configure\Engine\PhpConfig;
- // Read config files from config
- Configure::config('default', new PhpConfig());
- // Read config files from another path.
- Configure::config('default', new PhpConfig('/path/to/your/config/files/'));
You can have multiple engines attached to Configure, each reading differentkinds or sources of configuration files. You can interact with attached enginesusing a few other methods on Configure. To check which engine aliases areattached you can use Configure::configured()
:
- // Get the array of aliases for attached engines.
- Configure::configured();
- // Check if a specific engine is attached
- Configure::configured('default');
You can also remove attached engines. Configure::drop('default')
would remove the default engine alias. Any future attempts to load configurationfiles with that engine would fail:
- Configure::drop('default');
Loading Configuration Files
Once you’ve attached a config engine to Configure you can load configurationfiles:
- // Load my_file.php using the 'default' engine object.
- Configure::load('my_file', 'default');
Loaded configuration files merge their data with the existing runtimeconfiguration in Configure. This allows you to overwrite and add new values intothe existing runtime configuration. By setting $merge
to true
, valueswill not ever overwrite the existing configuration.
Creating or Modifying Configuration Files
Dumps all or some of the data in Configure into a file or storage systemsupported by a config engine. The serialization format is decided by the configengine attached as $config. For example, if the ‘default’ engine isa Cake\Core\Configure\Engine\PhpConfig
, the generated file will bea PHP configuration file loadable by theCake\Core\Configure\Engine\PhpConfig
Given that the ‘default’ engine is an instance of PhpConfig.Save all data in Configure to the file my_config.php:
- Configure::dump('my_config', 'default');
Save only the error handling configuration:
- Configure::dump('error', 'default', ['Error', 'Exception']);
Configure::dump()
can be used to either modify or overwriteconfiguration files that are readable with Configure::load()
Storing Runtime Configuration
You can also store runtime configuration values for use in a future request.Since configure only remembers values for the current request, you willneed to store any modified configuration information if you want touse it in subsequent requests:
- // 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 named cache configuration. See theCaching documentation for more information on caching.
Restoring Runtime Configuration
Once you’ve stored runtime configuration, you’ll probably need to restore itso you can access it again. Configure::restore()
does exactly that:
- // Restore runtime configuration from the cache.
- Configure::restore('user_1234', 'default');
When restoring configuration information it’s important to restore it withthe same key, and cache configuration as was used to store it. Restoredinformation is merged on top of the existing runtime configuration.
Configuration Engines
CakePHP provides the ability to load configuration files from a number ofdifferent sources, and features a pluggable system for creating your ownconfiguration engines.The built in configuration engines are:
By default your application will use PhpConfig
.
Disabling Generic Tables
While utilizing generic table classes - also called auto-tables - when quicklycreating new applications and baking models is useful, generic table class canmake debugging more difficult in some scenarios.
You can check if any query was emitted from a generic table class via DebugKitvia the SQL panel in DebugKit. If you’re still having trouble diagnosing anissue that could be caused by auto-tables, you can throw an exception whenCakePHP implicitly uses a generic Cake\ORM\Table
instead of your concreteclass like so:
- // In your bootstrap.php
- use Cake\Event\EventManager;
- use Cake\Http\Exception\InternalErrorException;
- $isCakeBakeShellRunning = (PHP_SAPI === 'cli' && isset($argv[1]) && $argv[1] === 'bake');
- if (!$isCakeBakeShellRunning) {
- EventManager::instance()->on('Model.initialize', function($event) {
- $subject = $event->getSubject();
- if (get_class($subject) === 'Cake\ORM\Table') {
- $msg = sprintf(
- 'Missing table class or incorrect alias when registering table class for database table %s.',
- $subject->getTable());
- throw new InternalErrorException($msg);
- }
- });
- }