Of all the PHP frameworks I’ve worked with to date, none of them used constants to store database connection data (and other things, for example).
I often see this use of constants in older libraries.
In the CakePHP 2
, was used constants for database configuration, but it was within a class.
Example:
class DB_CONFIG
{
const HOST = 'nome_do_host';
...
}
In the Laravel 4 e 5
, use a configuration file that returns a array
with the connection data, being read only by the location where it is included.
The Symfony 2
uses yaml
by default, other options may also be used.
I would not recommend the use of constants, unless it was a specific namespace or a class, as in Cakephp 2
.
It is also worth remembering that, regardless of the ways I highlighted and idependente to use constant or not, all of the above were unanimous in one thing: The configuration location 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 script output data, which generates a lot of confusion.
In the end, what can matter is more the organization than the medium itself where the data is stored.
It is worth remembering that in the versions of PHP 5.6 >=
, we can use array
constants. This makes it easier to use than to use prefixes for constants.
PHP Example Currently:
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASSWORD', 'SENHA');
Exmeplo PHP 5.6 >:
define('DB', [
'HOST' => 'localhost',
'USER' => 'username',
'PASSWORD' => 'SENHA'
]);
OR
const DB = [ 'HOST' => 'localhost', ...];
Other forms
In PHP it is also possible to use files ini
and json
.
In the case of json
:
config.json
{
"DB": {
"HOST" : 'localhost'
}
}
Loading the 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 its content as text, if it is listed
Very interesting this solution, but in case I use an INI for example, it would be good to have a class (model) just to read and bring this information when necessary, correct?
– Renan Cavalieri
Also possible! It would be more interesting if this model detected on index
[DB]
and[DB_LOCAL]
, for you already configure once only the connection data in production (as in Laravel). Hence you only need to inform your application whether it is in production or local for it to perform connection data exchange automatically– Wallace Maxters
I will give a study in Laravel, although I want to avoid the use of frameworks because I am learning and developing a CMS from scratch (just for study), I think learning from them will help a lot.
– Renan Cavalieri