Is it recommended to use constants for a PHP project's settings?

13

It is very common to see constants in a configuration file in a PHP project, however I would like to know if this is really the best practice, as I think if I store the password of a database in a config.php it could be used anywhere, that is, accessible throughout my project, I do not know if this would fit the standard (or anti-default) "God Object", but would be the constants the best solution for this type of problem?

    
asked by anonymous 18.11.2015 / 17:05

8 answers

13

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

    
18.11.2015 / 17:54
7
The constant is not a recommendation to use in settings , it's a way of keeping a constant data throughout your project, which will be used repeatedly in multiple places.

In several situations, we can have constants with data that will be kept throughout your project, like the two examples below:

//resumo da constante do php de diretório    
define('DS', DIRECTORY_SEPARATOR); 
//caminho físico da aplicação
define('APPLICATION_PATH', '..' . DS . dirname(__DIR__) . DS);  

What makes it different is the "manual" ease of maintenance (if necessary, which is hardly likely to be).

One of the recommendations for use is in your aggregation of events defined with setEnv , which may be setting parameters for the development environment. As the Zend Framework already uses in host virtualization:

yourproject.conf

<VirtualHost *:80>
     ServerName yourproject.local
     DocumentRoot /var/www/YourProject/public
     SetEnv APPLICATION_ENV "development"
     <Directory /var/www/YourProject/publicc>
          DirectoryIndex index.php
          AllowOverride All
          Order allow,deny
          Allow from all
     </Directory>
</VirtualHost>

PHP

// Define application environment
defined('APPLICATION_ENV') ||
define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ?
getenv('APPLICATION_ENV') : 'production'));

That is, when using constant, assume that it will be something that will not change ( never? who knows ... ).

In short: constant is what the name itself and its behavior says, something constant, that does not change. If you have something like this in your application, use , so you do not have to shred later lumps of things you never need to change.

Example of using constant with class:

class AppPath
{
   const APPLICATION_PATH = "/path/app/";

   public function __construct()
   {
       echo self::APPLICATION_PATH;
   }
}

//instanciando a classe, o construtor retornará a constante
return new AppPath(); 
    
18.11.2015 / 17:50
6

I think this can not be considered god object , it does not even seem to be an object, maybe I wanted to talk about something else.

This is not the best practice, but it is very much practiced without causing major problems in practice. It depends on how secure you need to access the data. Obviously with the password exposed, other people who have access to the server, will have access to the bank. But the bank will probably not be encrypted either, so it makes little difference.

If you need security in effect, authentication can not be done this way, you would need access to the bank to be done only with password passed by the user in a secure way. What is not feasible in case the user is anonymous. Then you could use a password stored somewhere but encrypted. This does not mean that security is absolute.

It does not make any difference to be constant, or to be stored in another way. It will not change anything put in another way, Constants should be avoided, but some that clearly have global function, have no problems.

    
18.11.2015 / 17:19
4

It depends a lot on the type of configuration you want to store and the architecture of your system. For example, settings that are managed by user, for example: color, size, style, layout and etc would be preferable not to store in constants, because as the name itself says, they are constants and so should remain with a single value a from the moment they are set.

However, if your system has a unique login and you need to make use of the client's password, I see no problem in creating a constant with the password. As long as the value of it does not change during the execution of the program.

    
18.11.2015 / 17:16
4

Passwords and access data I already prefer #

    
18.11.2015 / 17:17
4

Constants are used as pieces of information reusable from formal (generally) global and immutable, ie do not change.

In case you create a password constant for your database, it is strongly recommended that it be encrypted before the setting.

When God object is basically a class or object that functions as a repository of functions, class / object has more than one responsibility.

    
18.11.2015 / 17:19
3

Better to centralize your data in a configuration file.

If you're going to use with define, or if you're going to use an .env (dotEnv), it does not make much difference.

Just do not leave it fixed in the code as it makes maintenance difficult.

    
18.11.2015 / 17:19
2

You should use constants only to store information that does not change and should be accessible anywhere in the project .

In all other cases, I recommend that you use an accessible configuration file through a configuration class

Example: Config::get( 'databases.main' ) .

    
08.12.2015 / 13:51