What's the best way to get config variables in a class in php 5?

This is for my DB class. I'm new to OO, have been a procedural guy for a while now, so I'm still a little gloomy.

My first idea was to use a lot of setter functions / methods. But after writing a whole group, I thought about using PHP's definition function, eg.

define('MYSQL_USERNAME', 'jimbo');

      

Is this a common practice? What's the best practice? Should I really clutter my class with a lot of setter functions (I'm currently the only developer using these classes). What are your solutions?

Thank!

+1


source to share


3 answers


I const

only use to create mnemonic names for immutable constants in a class. The function define()

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 a hash array protected

in a class. Keys are useful for mnemonics. Default values.



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

      

Then I load the "ini" format file with parse_ini_file()

and use array_merge()

to map the keys in your class config array:

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

}

      

+2


source


maybe there are several options for this:



  • just use setters, this is fine, but can be a little verbose with a lot of configuration options.

  • use a config object to pass:

    $config = (object) array(
       'prop1' => 'somevalue',
       'prop2' => 'somevalue2',
       'prop3' => 'somevalue3',
    );
    
    $db = new DB($config);
    
          

  • If you want to use constants, you can restrict them to a class to avoid global namespace pollution:

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

+2


source


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

  • as @Owen recommends using class constants

    class Config {
        const PASSWORD_LENGTH = 12;
        const SEND_PASSWORD_EMAILS = true;
        // ...
    }
    
          

  • For simple config variables (i.e. no arrays, etc.) the vlucas / phpdotenv package available on composer does a great job. The file .env

    contains all of your configuration:

    PASSWORD_LENGTH=12
    SEND_PASSWORD_EMAILS=1
    
          

It is then available through getenv()

or $_ENV

superglobal.

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

      

0


source







All Articles