Of all the PHP frameworks I've worked on today, none of them used constants to save database connection data (and other things, for example).
I often see this use of constants in older libraries.
In% with%, constants were used for database configuration, however it was within a class.
Example:
class DB_CONFIG
{
const HOST = 'nome_do_host';
...
}
In CakePHP 2
, use a configuration file that returns a Laravel 4 e 5
with the connection data, being read only by the location where it is included.
array
uses Symfony 2
by default, and other options can also be used.
I would not recommend using constants, unless it was in a specific namespace or a class, as in yaml
.
It is also worth remembering that, regardless of the forms that I highlighted and idependente to use constant or not, all those highlighted above were unanimous in one thing: The place of configuration is separate and easy to find. This improves the life of the programmer, when it has to configure the application. Because it is common for people to mix script for configuration and output script, which creates a lot of confusion.
In the end, what you can import is more the organization than the medium itself where the data is stored.
Note that in Cakephp 2
versions, we can use PHP 5.6 >=
in constants. This makes it easier to use, rather than using prefixes for constants.
PHP Example Currently:
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASSWORD', 'SENHA');
PHP 5.6 > example:
define('DB', [
'HOST' => 'localhost',
'USER' => 'username',
'PASSWORD' => 'SENHA'
]);
OR
const DB = [ 'HOST' => 'localhost', ...];
Other ways
In PHP it is also possible to use array
and ini
files.
In the case of json
:
config.json
{
"DB": {
"HOST" : 'localhost'
}
}
Loading JSON:
json_decode(file_get_contents('config.json'));
Example ini:
config.ini
[DB]
HOST=localhost
PASSWORD=senha
In PHP:
parse_ini_file('config.ini', true);
Note : These last two cases should be separated into directories not accessible to the client, since the browser can read your content as text if it is listed