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:

  1. use Cake\Core\Configure;
  2. use Cake\Core\Configure\Engine\PhpConfig;
  3.  
  4. Configure::setConfig('default', new PhpConfig());
  5. Configure::load('app', 'default', false);
  6. 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:

  1. $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 not false, 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 the Host 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 theplugins, 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 is true
    • (string) ‘force’ - Always appends the timestamp.
  • Asset.cacheTime
  • Sets the asset cache time. This determines the http header Cache-Control’smax-age, and the http header’s Expire’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 to test_plugin/logo.png

If you set App.imageBaseUrl to https://mycdn.example.com/:

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:

  1. "autoload": {
  2. "psr-4": {
  3. "App\\Controller\\": "/path/to/directory/with/controller/folders/",
  4. "App\\": "src/"
  5. }
  6. }

The above would setup paths for both the App and App\Controllernamespace. 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:

  1. "autoload": {
  2. "psr-4": {
  3. "App\\": ["src/", "/path/to/directory/"]
  4. }
  5. }

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:

  1. return [
  2. // More configuration
  3. 'App' => [
  4. 'paths' => [
  5. 'plugins' => [
  6. ROOT . DS . 'plugins' . DS,
  7. '/path/to/other/plugins/'
  8. ],
  9. 'templates' => [
  10. ROOT . 'templates' . DS,
  11. ROOT . 'templates2' . DS
  12. ],
  13. 'locales' => [
  14. ROOT . 'resources' . DS . 'locales' . DS
  15. ]
  16. ]
  17. ]
  18. ];

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

  • class Cake\Core\Configure

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

  • static Cake\Core\Configure::write($key, $value)

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

  1. Configure::write('Company.name','Pizza, Inc.');
  2. 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:

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

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

  • static Cake\Core\Configure::read($key = null, $default = null)

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:

  1. // Returns 'Pizza Inc.'
  2. Configure::read('Company.name');
  3.  
  4. // Returns 'Pizza for your body and soul'
  5. Configure::read('Company.slogan');
  6.  
  7. Configure::read('Company');
  8. // Returns:
  9. ['name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul'];
  10.  
  11. // Returns 'fallback' as Company.nope is undefined.
  12. Configure::read('Company.nope', 'fallback');

If $key is left null, all values in Configure will be returned.

  • static Cake\Core\Configure::readOrFail($key)

Reads configuration data just like Cake\Core\Configure::readbut expects to find a key/value pair. In case the requested pair does notexist, a RuntimeException will be thrown:

  1. Configure::readOrFail('Company.name'); // Yields: 'Pizza, Inc.'
  2. Configure::readOrFail('Company.geolocation'); // Will throw an exception
  3.  
  4. Configure::readOrFail('Company');
  5.  
  6. // Yields:
  7. ['name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul'];

Checking to see if Configuration Data is Defined

  • static Cake\Core\Configure::check($key)

Used to check if a key/path exists and has non-null value:

  1. $exists = Configure::check('Company.name');

Deleting Configuration Data

  • static Cake\Core\Configure::delete($key)

Used to delete information from the application’s configuration:

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

Reading & Deleting Configuration Data

  • static Cake\Core\Configure::consume($key)

Read and delete a key from Configure. This is useful when you want tocombine reading and deleting values in a single operation.

  • static Cake\Core\Configure::consumeOrFail($key)

Consumes configuration data just like Cake\Core\Configure::consumebut expects to find a key/value pair. In case the requested pair does notexist, a RuntimeException will be thrown:

  1. Configure::consumeOrFail('Company.name'); // Yields: 'Pizza, Inc.'
  2. Configure::consumeOrFail('Company.geolocation'); // Will throw an exception
  3.  
  4. Configure::consumeOrFail('Company');
  5.  
  6. // Yields:
  7. ['name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul'];

Reading and writing configuration files

  • static Cake\Core\Configure::setConfig($name, $engine)

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():

  1. use Cake\Core\Configure\Engine\PhpConfig;
  2.  
  3. // Read config files from config
  4. Configure::config('default', new PhpConfig());
  5.  
  6. // Read config files from another path.
  7. 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():

  1. // Get the array of aliases for attached engines.
  2. Configure::configured();
  3.  
  4. // Check if a specific engine is attached
  5. Configure::configured('default');
  • static Cake\Core\Configure::drop($name)

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:

  1. Configure::drop('default');

Loading Configuration Files

  • static Cake\Core\Configure::load($key, $config = 'default', $merge = true)

Once you’ve attached a config engine to Configure you can load configurationfiles:

  1. // Load my_file.php using the 'default' engine object.
  2. 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

  • static Cake\Core\Configure::dump($key, $config = 'default', $keys = [])

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:

  1. Configure::dump('my_config', 'default');

Save only the error handling configuration:

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

  • static Cake\Core\Configure::store($name, $cacheConfig = 'default', $data = null)

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:

  1. // Store the current configuration in the 'user_1234' key in the 'default' cache.
  2. 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

  • static Cake\Core\Configure::restore($name, $cacheConfig = 'default')

Once you’ve stored runtime configuration, you’ll probably need to restore itso you can access it again. Configure::restore() does exactly that:

  1. // Restore runtime configuration from the cache.
  2. 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:

  1. // In your bootstrap.php
  2. use Cake\Event\EventManager;
  3. use Cake\Http\Exception\InternalErrorException;
  4.  
  5. $isCakeBakeShellRunning = (PHP_SAPI === 'cli' && isset($argv[1]) && $argv[1] === 'bake');
  6. if (!$isCakeBakeShellRunning) {
  7. EventManager::instance()->on('Model.initialize', function($event) {
  8. $subject = $event->getSubject();
  9. if (get_class($subject) === 'Cake\ORM\Table') {
  10. $msg = sprintf(
  11. 'Missing table class or incorrect alias when registering table class for database table %s.',
  12. $subject->getTable());
  13. throw new InternalErrorException($msg);
  14. }
  15. });
  16. }