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
    

Need Your Help

Session timeout not working for CHttpSession in Yii framework

php session yii yii-components

I am creating an web application in Yii . I was trying to do a sessiontimeout, if a user is idle for 30 minutes.After that he should login again.. but this is not working. I am using CHttpSession.

facebook sharer.php error chrome

javascript facebook google-chrome

I am using the sharer button inside a facebook app. It works in all browsers except Chrome.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.