What is the best way to get config variables into a class in php 5?

This is for my DB class. I am new to OO, been a procedural lad for some time, so I'm still a bit murky.

My first idea was using a bunch of setter functions/methods.. but after writing a whole bunch, I thought about using PHP's define function, like so.

define('MYSQL_USERNAME', 'jimbo');

Is this an accepted practice? What is the best practice? Should I really clutter my class with a bunch of setter functions (I am currently the only developer using these classes). What are your solutions?

Thank you!

Answers


I use const only for creating mnemonic names for immutable constants in the class. The define() function does not create constants as part of the class, it creates constants in the global space.

class MyClass
{
  const CONFIG_FILE = 'myapp.ini';

Class configuration data I usually declare as a protected hash-array in the class. Keys are useful for mnemonics. Values are defaults.

  protected $config = array(
    'logfile' => 'err.out',
    'debug' => false
  );

Then I load an "ini" format file with parse_ini_file() and use array_merge() to map the keys into your class config array:

  public function __construct() {
    $ini_data = parse_ini_file(self::CONFIG_FILE, __CLASS__);
    $this->config = array_merge($this->config, $ini_data);
  }

}

there are probably a few options to deal with this:

  1. just use setters, it's perfectly acceptable, but can get a bit "wordy" with a lot of config options.

  2. use a config object to pass in:

    $config = (object) array(
       'prop1' => 'somevalue',
       'prop2' => 'somevalue2',
       'prop3' => 'somevalue3',
    );
    
    $db = new DB($config);
    
  3. if you want to use constants, you could restrict them to the class to avoid global namespace pollution:

    class DB {
        const USER = 'mysqluser';
    }
    
    echo DB::USER; // for example
    

I've had good success at doing this in two ways:

  1. as @Owen recommends, using class constants

    class Config {
        const PASSWORD_LENGTH = 12;
        const SEND_PASSWORD_EMAILS = true;
        // ...
    }
    
  2. For simple config variables (i.e. no arrays etc) the package vlucas/phpdotenv, available on composer, does a great job. A file .env contains all your config:

    PASSWORD_LENGTH=12
    SEND_PASSWORD_EMAILS=1
    

This is then made available via getenv() or the $_ENV superglobal.

    Dotenv::load(__DIR__);
    $passwordLength = $_ENV['PASSWORD_LENGTH']

Need Your Help

Do some math over two columns of a .dat file and save results into a third column

python csv file-io

In python, having a .dat file with two columns, let say [a1, a2, ... an] at the first column and [b1, b2, ... bn] at the second one, how can I do some math in terms of the components of column1 and