Question

I use a global array to define certain configurations for my application. But so far I've read that globals are bad practice and should be avoided. This global is read-only, so I'm not altering it in any way in my code.

What would be the correct way of defining configuration settings?

$GLOBALS['config'] = array(
    'mysql' => array(
        'host'     => 'localhost',
        'username' => 'user',
        'password' => 'password',
        'database' => 'database'
    ),
    'navigation' => array(
        'Home'    => array('/', '/index.php'),
        'Sign up' => array('/signup', '/signup.php'),
        'Log in'  => array('/login', '/login.php')
    )
);
Was it helpful?

Solution

Start with a Configuration class to hold all settings in a collection of key->value pairs and getter and setter methods. This class is part of the normal application code.

To be able to handle different settings for each environment, like the connection parameters in your example, use multiple files.

For each environment a folder exists to store the all environment-specific configuration files.

One of the files stored here is a script that:

  • creates a static configuration object
  • sets all configuration parameters to the values for that environment.

Other parts of the application use this static object to get the settings from.

The files in the different folders have equal names, for example in this structure:

- config
  - development
    - config.php
  - staging
    - config.php
  - production
    - config.php

During deployment the configuration files for the environment that you are deploying to are included. What I do is also put the deployment scripts in these folders.

This setup supports multiple environments and you can keep the files with configuration settings under version control.

OTHER TIPS

I don't have much of an idea of PHP. But with respect to OOP, you can create a class(possibly named Config) which contains static read-only variables. And then use them as follows

Config.mysql and Config.navigation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top