Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Configuration

Settings are values that differ between computers or change without editing code: the database address, debug mode, the site name. In CakePHP they are stored in the config folder.

Three files

FileWhat it holdsIn the repository
config/app.phpDefault settings shared by everyoneYes
config/app_local.phpSettings of this computer: passwords, keysNo
config/.envEnvironment variables, an optional fileNo

app_local.php is created automatically during project installation from the app_local.example.php sample. Its values replace the values from app.php.

How a file is built

Each file returns an array with sections:

// config/app_local.php
return [
    'debug' => true,
 
    'Security' => [
        'salt' => 'a-long-random-string',
    ],
];

debug turns on development mode: detailed error pages and the DebugKit panel. Security.salt is a secret string for encryption, unique to every project.

Reading settings

use Cake\Core\Configure;
 
$debug = Configure::read('debug');
$salt = Configure::read('Security.salt');

Configure::read() is available anywhere in the code. A dot in the key goes deeper into the array: Security.salt is the salt key of the Security section.

Your own settings

Add your own section to config/app.php:

// config/app.php
'Blog' => [
    'name' => 'My blog',
    'perPage' => 10,
],

Use it in a controller action:

$this->set('siteName', Configure::read('Blog.name'));
$perPage = Configure::read('Blog.perPage', 20);

The second argument is the value used when the key is missing. The site name is now changed in one place.

Environment variables

The env() function reads an environment variable, a value set by the server itself:

// config/app_local.php
'debug' => filter_var(env('DEBUG', true), FILTER_VALIDATE_BOOLEAN),

If there is no DEBUG variable, the default value true is used.

The .env file

On a developer's computer it is convenient to keep variables in a file. Copy config/.env.example to config/.env and uncomment the block in config/bootstrap.php that loads this file. The file format:

export APP_NAME="blog"
export DEBUG="true"
export SECURITY_SALT="a-long-random-string"

After that env('APP_NAME') returns blog.

Common mistake

A database password or a payment service key written in config/app.php gets into the repository and becomes visible to everyone with access to the code. Keep secrets in app_local.php or in .env; these files are listed in .gitignore.

Thanks for reading!

Donate to the site — we work hard for you.